I'm trying to implement a library where Class1 provides about five public methods Method1 to Method5. Class2 provides two methods - Methods6 and Method7. And Class3 provides one method - Method8. Now, for the end user, I want to expose methods from combination of these classes. E.g. If the end user instantiates a class called Class1Class2, they should have access to Method1 to Method7, if they instantiate a class called Class1Class3, they should have access to Method1 to Method5 and Method8.
There are 3 different approaches I could think of (please suggest any others as well):
(1) Multiple inheritance: Keep each of Class1, Class2 and Class3 as it is. Then, create a new class Class1Class2 that publicly multiple inherits from Class1 and Class2. Similarly I can create a class Class1Class3 that publicly multiple inherits from Class1 and Class3.
(2) Multi-level inheritance: I could derive Class2 from Class1, and call that Class1Class2. And Class3 from Class1 and call that Class1Class3. And if we need Class1Class2Class3, we inherit that class from Class2 and Class3, which have both derived from Class1. Here, we would use virtual inheritance to resolve the diamond problem. I don't expect to use Class2Class3, so that shouldn't be a problem here.
(3) Composition: Keep each of Class1, Class2 and Class3 as it is. Create Class1Class2 that implements each of the methods Method1 to Method7 and internally delegate them to the objects of Class1 and Class2 accordingly. Similarly, a Class1Class3 would compose objects of Class1 and Class3. With this approach we need to provide implementations for all the methods and delegate them to the composed objects.
While "Composition over inheritance" guideline is generally great for loose coupling of classes, etc., in the above case, where we have to do code reuse from separate concrete implementations, Approach 1 or 2 seem like better options.
I'd appreciate any thoughts on this.
Aucun commentaire:
Enregistrer un commentaire