简体   繁体   English

具有相同实现但基类不同的2个类的C#设计模式

[英]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. 取两个基类A和B,它们相似但最好是不同的。 Each has a sub class (A' and B') which add the same functionality and members to their respective classes. 每个子类都有一个子类(A'和B'),它们将相同的功能和成员添加到它们各自的类中。 Is there a design pattern to allow me to not have to duplicate code in A' and B'? 是否有设计模式允许我不必重复A'和B'中的代码?

I've looked at Bridge and Decorator , but I can't see how these would work. 我看过BridgeDecorator ,但我看不出它们是如何工作的。

Thanks, Rob 谢谢,罗布

你可以使用组合并将共享代码重构为另一个类C吗?

Take two base classes A and B which are similar but are preferred to be distinct. 取两个基类A和B,它们相似但最好是不同的。 Each has a sub class (A' and B') which add the same functionality and members to their respective classes. 每个子类都有一个子类(A'和B'),它们将相同的功能和成员添加到它们各自的类中。

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. 假设这是不合理的,无论出于何种原因,我认为Decorator是最好的,可以避免代码重复。

You will need to create the subclasses, A' & B'. 您需要创建子类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'. 该类的实例将包含在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'. 在第三个类中创建公共代码,并在A'和B'中保存一个实例。

add the same functionality and members to their respective classes . 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? 也许类似于Provider模式? http://msdn.microsoft.com/en-us/library/ms972319.aspx http://msdn.microsoft.com/en-us/library/ms972319.aspx

The concept of mixins comes close to that what you want. mixin的概念接近你想要的。 However this concept is not natively supported by C#. 但是,C#本身不支持此概念。 You can use interfaces and extension methods to mimic the concept of mixins, but it does not look very pretty. 您可以使用接口和扩展方法来模仿mixins的概念,但它看起来不太漂亮。

Have a look on this question for further information: Is it possible to implement mixins in C#? 有关更多信息,请查看此问题: 是否可以在C#中实现mixins?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM