请查看以下问题:Favor composition over inheritance
接受的回答者说:“它扩展了Hashtable,以便重用其方法并避免使用委托重新实现其中的一些”。我不确定回答者的意思是:使用委托重新实现其中的一些。回答者的意思是什么?
我熟悉Delegates和Observer设计模式。
答案 0 :(得分:5)
使用组合时,如果要支持基础类具有的方法,则必须定义自己的实现,该实现只是在基础类上委托(或使用)相同的方法。在这种情况下使用继承可能很有诱惑力,以避免编写这种简单(委托)方法,但只有在存在IS-A关系时才应该使用继承。
例如,
public class Foo
{
public virtual void Bar()
{
// do something
}
}
public class InheritedFromFoo : Foo
{
// we get Bar() for free!!!
}
public class ComposedWithFoo
{
private Foo _foo;
public void Bar()
{
_foo.Bar(); // delegated to the Foo instance
}
}