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

Rom*_*Ukr 3 c# design-patterns

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

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

Wik*_*hla 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 )
    {
    }
}
Run Code Online (Sandbox Code Playgroud)


Agh*_*oub 5

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

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

=>匹配不同类的接口

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

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