Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can subclasses share behavior when one already derives from a different base class?

I have two classes that implement ISomeBehavior. Now I want them to share functionality. Normally I would replace ISomeBehavior with an abstract class, like SomeBehaviorBase. The problem is that one of the subclasses already derives from another class, and that other class isn’t software we own. (This is C#, so multiple inheritance isn't an option.) The subclass, that derives from the 3rd party class, has no implementation. It simply derives from the 3rd party class, and implements ISomeBehavior, so the 3rd party class can be treated the same way as the other subclasses that implement ISomeBehavior.

What I've done, for the moment, is implement an extension method on ISomeBehavior. Now the consuming code can call the method. The problem with that approach is that I want to force the calling code to use this extension method. I can't remove SomeMethod() from the interface, because the extension method has to eventually call it.

Any ideas on how to let two classes elegantly share the same behavior, when one of them already derives from another, third party, class? Note: The strategy design pattern sounds like it makes sense here, but that pattern is used when behavior varies among subclasses. The behavior here doesn't vary; it just needs to be shared.

like image 548
Bob Horn Avatar asked Feb 18 '11 14:02

Bob Horn


People also ask

What happens when you make a new class a subclass of another class?

What happens when you make a new class a subclass of another class? a. The new class inherits the attributes and behaviors defined in the parent class.

When a subclass inherits from multiple base classes?

Multiple Inheritance - When a subclass inherits properties from multiple base classes, it is known as multiple inheritance. In multiple Inheritance , there is only one derived class and several base classes.

Can subclasses have their own methods?

A subclass can do more than that; it can define a method that has exactly the same method signature (name and argument types) as a method in its superclass.

Do subclasses automatically inherit methods?

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.


1 Answers

Is there any reason you can't use composition instead of delegation to implement the class which currently derives from the 3rd party class? Just delegate all the interface methods to an instance of the third party class. That way, if you want to add functionality you can use a common base class.

This won't work in some cases where the object identity is relevant, but in many cases it's a perfectly reasonable design.

like image 135
Jon Skeet Avatar answered Oct 09 '22 03:10

Jon Skeet