Decorator和Adapter模式之间有什么区别?

时间:2013-07-18 18:45:27

标签: c# design-patterns

在什么条件下使用Adapter或Decorator模式会更好?

欢迎来自真实节目的例子。

2 个答案:

答案 0 :(得分:12)

我不认为这些可以互换使用。

适配器更改对象的接口以使其适应另一个接口。 Decorator在添加功能时维护界面。

public class Foo
{
}

public class Bar
{
}

// adapter takes Foo and pretends it is Bar
public class FooBarAdapter : Bar
{
   public FooBarAdapter( Foo foo )
   {
   }
}

// decorator maintains the interface and adds features
public class FooDecorator : Foo
{
    public FooDecorator( Foo foo )
    {
    }
}

答案 1 :(得分:5)

你有这些与uml图代码的链接并解释

适配器:http://www.dofactory.com/Patterns/PatternAdapter.aspx

=>匹配不同类的接口

装饰者:http://www.dofactory.com/Patterns/PatternDecorator.aspx

=>动态地向对象添加职责

相关问题