How can subclasses share their behavior when it already comes from another 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, such as SomeBehaviorBase. The problem is that one of the subclasses already comes from another class, and the other class is not the software that we own. (This is C #, so multiple inheritance is not an option.) A subclass that derives from a third-party class has no implementation. It simply stems from the third class and implements ISomeBehavior, so a third-party class can be handled in the same way as other subclasses that implement ISomeBehavior.

What I have done, at the moment, implements the extension method on ISomeBehavior. Now the consumption code can call the method. The problem with this approach is that I want to force the calling code to use this extension method. I cannot remove SomeMethod () from the interface because the extension method should eventually call it.

Any ideas on how two classes elegantly share the same behavior when one of them already comes from the other, third person, class? Note. The strategy design pattern sounds like it makes sense here, but this pattern is used when the behavior varies between subclasses. The behavior here does not change; it just needs to be exchanged.

+6
c # subclass behavior share
source share
4 answers

Is there a reason you cannot use composition instead of delegation to implement the class that is currently derived from the third class? Just pass all the interface methods to a third-party instance. Thus, if you want to add functionality, you can use a common base class.

This will not work in some cases where the identity of the object is relevant, but in many cases it is a perfectly reasonable design.

+5
source share

Here is a good article on this topic: http://www.codeproject.com/KB/architecture/smip.aspx

GJ

+2
source share
public interface ISomeBehavior { int Sample(); } public class A : ISomeBehavior { int ISomeBehavior.Sample() { return 1; } } static class SomeExtension { public static int Sample(this ISomeBehavior obj) { return 2; } } 

and then use this

  A a = new A(); var a1 = ((ISomeBehavior)a).Sample(); // a1 = 1 var a2 = a.Sample(); // a2 = 2 
0
source share

How about something like this:

 class MyClass: ThirdPartyClass { } class MyFunctionality { public MyFunctionality(ThirdPartyClass target) ... } interface IMyFunctionality { public MyFunctionality MyFunctionality; } 

Thus, the interface will ensure that the derived class must create an instance of the superscript element, and the MyFunctionality design will only act against the reference to the base class. This may not work if there are protected members who need internal access.

0
source share

All Articles