两个不同类的运行时多态性

Runtime polymorphism for two different classes

本文关键字:同类 运行时 多态性 两个      更新时间:2023-10-16

>我有两个类BY,我无法根据需要更改或编辑。它们具有执行相同操作但名称不同的函数。

我想有一个通用接口,可以在运行时根据某些输入变量选择类,如下代码中所述。我不确定我应该使用哪种设计模式。如何创建WrapperYB类,该类根据创建的对象选择Y::showB::showing

class A
{
public:
    A() {}
    virtual ~A();
    virtual void show() { cout << "show A" << endl;}
};

class B:A
{
public:
    B() {}
    virtual ~B();
    virtual void show() { cout << "show B" << endl;}
};

class X
{
    char m_i;
public:
    Y() {  m_i = 'X';}
    virtual void showing() { cout << "showing " << m_i   << endl;}
};
class Y:X
{
public:
    Y() {  m_i = 'Y';}
    virtual void showing() { cout << "showing " << m_i   << endl;}
};

class WrapperYB
{
    // to be implemented
public:
    explicit WrapperYB(const int& type);
    void show();
};
int main(){
    WrapperYB objY(1);
    objY.show(); // must call Y::showing
    WrapperYB objB(0);
    objB.show(); // must call B::show
}

如果您的编译器支持 C++17 标准,您可以使用 std::variant 尝试此解决方案。 这与@Nicolas答案中的解决方案类似,但variant将为您处理实现细节,不会使用动态内存分配,并支持复制和分配等其他功能。

#include <variant>
#include <utility>
#include <type_traits>
class WrapperYB {
public:
    using variant_type = std::variant<Y, B>;
    template <typename... Args,
        std::enable_if_t<std::is_constructible_v<variant_type, Args...>>* = nullptr>
    WrapperYB(Args&& ... args) : m_variant(std::forward<Args>(args)...) {}
    variant_type& variant() noexcept { return m_variant; }
    const variant_type& variant() const noexcept { return m_variant; }
    void show()
    { std::visit(ShowImpl{}, m_variant); }
private:
    struct ShowImpl {
        void operator() (Y& y) const { y.showing(); }
        void operator() (B& b) const { b.show(); }
    };
    variant_type m_variant;
};

请参阅关于 coliru 的完整工作示例。

您可以通过让包装器包含std::unique_ptr<A>std::unique_ptr<X>来概括包装器。

我提议这个:

#include <iostream>
using namespace std;
class A
{
public:
    A() {}
    virtual ~A() {}
    virtual void show() { cout << "show A" << endl;}
};

class B:A
{
public:
    B() {}
    virtual ~B() {}
    virtual void show() { cout << "show B" << endl;}
};
class X
{
protected:
    char m_i;
public:
    X () {  m_i = 'X';}
    virtual void showing() { cout << "showing " << m_i   << endl;}
};
class Y:X
{
public:
    Y() {  m_i = 'Y';}
    virtual void showing() { cout << "showing " << m_i   << endl;}
};
class WrapperYB
{
public:
    enum class Which { B, Y };
public:
    explicit WrapperYB (int n)
        : which(Which(n))
    {
        switch (which)
        {
            case Which::B: ptr.b = new B; break;
            case Which::Y: ptr.y = new Y; break;
        }
    }
    ~WrapperYB ()
    {
        switch (which)
        {
            case Which::B: delete ptr.b; break;
            case Which::Y: delete ptr.y; break;
        }
    }
    WrapperYB (const WrapperYB&) = delete;
    WrapperYB& operator = (const WrapperYB&) = delete;
public:
    void show()
    {
        switch (which)
        {
            case Which::B: ptr.b->show()   ; break;
            case Which::Y: ptr.y->showing(); break;
        }
    }
private:
    Which which;
    union {
        Y* y;
        B* b;
    } ptr;
};
int main(){
    WrapperYB objY(1);
    objY.show(); // must call Y::showing
    WrapperYB objB(0);
    objB.show(); // must call B::show
}

我不认为这是一种"香草"设计模式,更多的是适配器和区别结合的结合。

请注意,不能按原样复制或分配 WrapperYB。

您可以将标准虚拟调度方法与抽象基适配器类和子类一起使用,用于所需的每个对象类型。使用工厂方法创建对象。

#include <memory>
//pre-defined structures Y, B
struct Y
{
    Y(){}
    ~Y(){}
    void show(){}
};
struct B
{
    B(){}
    ~B(){}
    void showing(){}
};
// Abstract adaptor base class. 
struct Adaptor
{
    virtual void show() = 0;
};
// A subclass of Adaptor for each type of object to be wrapped. 
struct Adaptor_Y: Adaptor
{
    Adaptor_Y(): y(){}
    void show() override
    {
        y.show();
    }
private:
    Y y;
};
struct Adaptor_B: Adaptor
{
    Adaptor_B(): b(){}
    void show() override
    {
        b.showing();
    }
private:
    B b;
};
// Factory method constructs the proper object and returns a pointer.
std::unique_ptr<Adaptor> get_adaptor(int flag)
{
    if(flag == 0)
    {
        return std::make_unique<Adaptor_B>();
    }
    else if(flag == 1)
    {
        return std::make_unique<Adaptor_Y>();
    }
    else throw std::runtime_error("Invalid flag value");
}