开发者

C# Design Pattern for 2 classes with same implementation but different base class

Take two base classes A and B which are similar but are preferred to be distinct. Each has a sub class (A' and B') which add the same functionality and members to their respective classes. Is there a design pattern to allow me to not have t开发者_StackOverflow中文版o duplicate code in A' and B'?

I've looked at Bridge and Decorator, but I can't see how these would work.

Thanks, Rob


Could you use composition and refactor the shared code to another class C?


Take two base classes A and B which are similar but are preferred to be distinct. Each has a sub class (A' and B') which add the same functionality and members to their respective classes.

This is a bit of an odd place to start from. If it were me, I'd be looking to change this part of the design.

Assuming that's not reasonable, for whatever reason, I think Decorator is about the best you can do to avoid code duplication.

You will need to create the subclasses, A' & B'. And you'll have to declare the added methods and properties in each. Those members should delegate to members of another class that can implement the common functionality. An instance of that class will be contained in both A' & B'.

This really only saves you duplication if the implementation of those common members is significant.


The strategy pattern. Create the common code in a third class, and hold an instance to it in A' and B'.


add the same functionality and members to their respective classes. Sounds close to an interface, though that would still have separate implementations. Maybe something similar to the Provider pattern? http://msdn.microsoft.com/en-us/library/ms972319.aspx


The concept of mixins comes close to that what you want. However this concept is not natively supported by C#. You can use interfaces and extension methods to mimic the concept of mixins, but it does not look very pretty.

Have a look on this question for further information: Is it possible to implement mixins in C#?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜