简体   繁体   中英

Factory Pattern with Multiple Inheritance

In this problem I have three pure virtual classes, let's name them A, B, C . Each of them provides a different set of functionality. I have another pure virtual class that I will call CommonInterface that does not introduce any new functionality but inherits A, B, and C to make them reachable through a single interface as below:

class CommonInterface : public virtual A, public virtual B, public virtual C

These interfaces are defined by a standard document and are not subject to change. They are defined as a factory design pattern, such that, anyone can implement the functionality of CommonInterface according to their needs.

My role is to provide a built-in implementation to this CommonInterface, so that people can use my implementation in case the built-in implementation of the interface is good enough for them. I want to design the built-in implementation well but I am not very sure how to apply the factory pattern to multiple inheritance cases. My current implementation implements each base interface as

class BuiltinA : public A
class BuiltinB : public B
class BuiltinC : public C

and then implements common interface as given below:

class BuiltinImplementation : public virtual CommonInterface, public BuiltinA, public BuiltinB, public BuiltinC

Is this a good or bad design? If it is a bad design, how can I improve it? Also is there any patterns I can apply to this case? Any expert opinion is welcome. Thanks in advance.

A CommonInterface of three classes should give you access to methods, that are purely common between all three classes and hide class specific interfaces. Your implementation of the CommonInterface gives the caller access to all class specific methods. I would consider this already a bad design.

I would propose to change the inheritance to:

class CommonInterface {
   public:
      virtual void common_method(<args>) = 0;
};

class A : public CommonInterface {
   public:
      virtual void a_specific_method(<args>) = 0;
};

class B : public CommonInterface {
   public:
      virtual void b_specific_method(<args>) = 0;
};

And your implementation of builtin is:

class Builtin_A : public A {
    [...]
};

class Builtin_B : public B {
    [...]
};

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