子类如何共享行为,当一个人已经从不同的基类派生? [英] How can subclasses share behavior when one already derives from a different base class?

查看:202
本文介绍了子类如何共享行为,当一个人已经从不同的基类派生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有实现ISomeBehavior两班。现在,我希望他们能够共享功能。通常我会用一个抽象类,像SomeBehaviorBase更换ISomeBehavior。问题是,在子类之一已经从另一个类派生,以及其他类不是我们自己的软件。 (这是C#,所以多重继承是不是一个选项。)的子类,从第三方类派生,没有实现。它只是从第三方类派生,并实现ISomeBehavior,所以第三方类可以被处理的方式实现ISomeBehavior其他子类相同。

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.

我'什么已经做了,就目前而言,是贯彻落实ISomeBehavior扩展方法。现在消费代码的可以的调用方法。这种做法的问题是,我想强制调用代码使用该扩展方法。我不能删除接口的someMethod(),因为扩展方法,最终调用它。

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.

推荐答案

有没有你不能使用成分代替代表团实现类任何理由,当前从第三方类派生?只是委托所有的接口方法的第三方类的一个实例。这样,如果你想添加的功能,你的可以的使用共同的基类。

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.

这篇关于子类如何共享行为,当一个人已经从不同的基类派生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆