装饰模式 Decorator
2017-04-08 11:43
127 查看
装饰模式 Decorator:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活
上图中
ConcreteComponent:定义了一个具体的对象,也可以对这个对象添加一些职责
ConcreteDecorator:具体装饰类对象,起到给Component添加职责的功能
Decorator:装饰抽象类,继承Component,扩展Component功能,但对Component无需知道Decorator存在
代码实现C#
创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
上图中
ConcreteComponent:定义了一个具体的对象,也可以对这个对象添加一些职责
ConcreteDecorator:具体装饰类对象,起到给Component添加职责的功能
Decorator:装饰抽象类,继承Component,扩展Component功能,但对Component无需知道Decorator存在
代码实现C#
//Component类 abstract class Component { public abstract void Operation(); } //ConcreteComponent类 class ConcreteComponent : Component { public override void Operation() { //具体操作 Console.WriteLine("具体操作"); } } abstract class Decorator : Component { protected Component component; public void SetComponent(Component component) { this.component = component;//设置component } public override void Operation() {//重写Operation(),实际执行Component的Operation() if (component != null) { component.Operation(); } } } class ConcreteDecoratorA : Decorator { private String addedState;//本类独有功能,区别ConcreteDecorator public override void Operation() { base.Operation();//先运行原Component的Operation,在执行本类功能,如addedState,相当于对Component进行装饰 addedState = "New state"; Console.WriteLine("具体装饰对象A的操作"); } } class ConcreteDecoratorB : Decorator { public override void Operation() { base.Operation();//先运行原Component的Operation,在执行本类功能, //如AddedBehavior(),相当于对Component进行装饰 AddedBehavior(); Console.WriteLine("具体装饰对象B的操作"); } private void AddedBehavior() { }//本类独特方法,以区别ConcreteDecoratorA }
//客户端代码 static void Main(string[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.SetComponent(c);//先用ConcreteComponent实例化对象c,然后用ConcreteComponentA的实例化对象d1包装c, //再用ConcreteDecoratorB的对象包装d1,最终执行d2的Operation() d2.SetComponent(d1); d2.Operation(); Console.Read(); }
创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
相关文章推荐
- .NET设计模式(10):装饰模式(Decorator Pattern)
- 设计模式之decorator装饰模式
- 装饰模式(Decorator/Wrapper Pattern)
- 设计模式之---装饰(decorator)
- 侃装饰模式(Decorator)
- 装饰(Decorator)模式
- 设计模式c#语言描述——装饰(Decorator)模式
- 设计模式之装饰模式篇(Decorator)
- 装饰(Decorator)模式
- 装饰模式Decorator Pattern
- 设计模式(11)-装饰模式(Decorator)
- 设计模式(9)-装饰模式(Decorator)
- 设计模式之装饰模式篇(Decorator)
- 装饰模式(Decorator Pattern)
- 装饰(Decorator)模式
- .NET设计模式(10):装饰模式(Decorator Pattern)
- 设计模式c#语言描述——装饰(Decorator)模式
- Decorator 装饰(结构型模式)
- 乐在其中设计模式(C#) - 装饰模式(Decorator Pattern)
- .NET设计模式-装饰模式(Decorator Pattern)