UML:
Component:定义一个对象接口,可以给这些对象动态的添加职责
ContreteComponent:定义了一个具体的对象,也可以给这个对象添加一些职责
Decorator:装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decrator的存在的
ContreteDecoratorA和ContreteDecoratorB都是具体的装饰对象,骑到给Component添加职责的功能
SAMPLE:
Component.cs
abstract class Component
{
public abstract void Operation();
}
{
public abstract void Operation();
}
ConcreteComponent.cs
1
class ConcreteComponent:Component
2 {
3 public override void Operation()
4 {
5 Console.WriteLine("具体对象的操作");
6 }
7 }
2 {
3 public override void Operation()
4 {
5 Console.WriteLine("具体对象的操作");
6 }
7 }
Decorator.cs
1
abstract class Decorator:Component
2 {
3 protected Component component;
4 public void setComponent(Component component)
5 {
6 this.component = component;
7 }
8 public override void Operation()
9 {
10 if (component != null)
11 component.Operation();
12 }
13 }
2 {
3 protected Component component;
4 public void setComponent(Component component)
5 {
6 this.component = component;
7 }
8 public override void Operation()
9 {
10 if (component != null)
11 component.Operation();
12 }
13 }
ConcreteDecoratorA.cs
1
class ConcreteDecoratorA : Decorator
2 {
3 private string addedState;
4 public override void Operation()
5 {
6 base.Operation();
7 addedState = "new state";
8 Console.WriteLine("具体装饰对象A的操作");
9 }
10 }
2 {
3 private string addedState;
4 public override void Operation()
5 {
6 base.Operation();
7 addedState = "new state";
8 Console.WriteLine("具体装饰对象A的操作");
9 }
10 }
ConcreteDecoratorB.cs
1
class ConcreteDecoratorB:Decorator
2 {
3 public override void Operation()
4 {
5 base.Operation();
6 addMethod();
7 Console.WriteLine("具体装饰对象B的操作");
8 }
9 //用来区别A方法
10 private void addMethod()
11 { }
12 }
2 {
3 public override void Operation()
4 {
5 base.Operation();
6 addMethod();
7 Console.WriteLine("具体装饰对象B的操作");
8 }
9 //用来区别A方法
10 private void addMethod()
11 { }
12 }
Program.cs
1
ConcreteComponent c = new ConcreteComponent();
2 ConcreteDecoratorA d1 = new ConcreteDecoratorA();
3 ConcreteDecoratorB d2 = new ConcreteDecoratorB();
4
5 d1.setComponent(c);
6 d2.setComponent(d2);
7 d2.Operation();
2 ConcreteDecoratorA d1 = new ConcreteDecoratorA();
3 ConcreteDecoratorB d2 = new ConcreteDecoratorB();
4
5 d1.setComponent(c);
6 d2.setComponent(d2);
7 d2.Operation();
装饰模式是利用setComponent来对付对象进行包装的.这样每个装饰独享的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中.