意图:动态地给对象增加一些额外的职责。
结构图:
public abstract class Component{
public abstract void Operation();
}
public class ConcreteComponent:Component{
public override void Operation(){
....
}
}
public abstract class Decorator : Component{
protected Component _component;
protected Decorator(Component component){
_component = component;
}
public override void Operation(){
if(_component != null){
_component.Operation();
}
}
}
public class ConcreteDecoratorA : Decorator{
public ConcreteDecorator(Component component) : base(component){}
public override void Operation(){
base.Operation();
.....
}
}
public class ConcreteDecoratorB : Decorator{
public ConcreteDecorator(Component component) : base(component){}
public override void Operation(){
base.Operation();
.....
}
}
public class Client{
static void Main(){
Component component = new ConcreteComponent();
Decorator decorator = new ConcreteDecoratorA(component);
decorator.Operation();
Decorator decorator1 = new ConcreteDecoratorB(decorator);
decorator1.Operation();
}
}
优点:
- 把抽象接口与实现解耦。
- 抽象与实现可以独立扩展,不会影响到对方。
- 实现细节对客户透明,隐藏了具体实现细节。
缺点:
增加了系统的复杂度。
来源:https://www.cnblogs.com/ljdong7/p/12572341.html