简体   繁体   中英

Runtime polymorphism for two different classes

I have two classes B and Y which I cannot change or edit by requirement. They have functions doing the same thing but with different names.

I want to a have a common interfaces with selecting the class at run time depending on the some input variable as described in the code below. I am not sure which design pattern should I use. How to create WrapperYB class which selects Y::show or B::showing depending on the object created.

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

}

If your compiler supports the C++17 Standard, you could try this solution using std::variant . This is a similar idea to the solution in @Nicolas's answer, but variant will take care of the implementation details for you, won't use dynamic memory allocation, and has support for additional things like copy and assignment.

#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;
};

See the full working example on coliru.

You might generalize the wrapper by letting it contain a std::unique_ptr<A> or std::unique_ptr<X> instead.

I'm proposing this:

#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
}

It's not a "Vanilla" design pattern, I don't think, and more of combination of adapter and discriminated union.

Note that WrapperYB cannot be copied or assigned, as is.

You can use a standard virtual dispatch method with an abstract base adaptor class and subclasses for each object type needed. Create the object with a factory method.

#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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM