简体   繁体   中英

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 to duplicate code in A' and B'?

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

Thanks, Rob

你可以使用组合并将共享代码重构为另一个类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#?

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