装饰模式 Decorator
来源:互联网 发布:java分布式开发框架 编辑:程序博客网 时间:2024/06/03 21:55
装饰模式 Decorator:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活
上图中
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(); }
创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
0 0
- 装饰模式Decorator Pattern
- 装饰(Decorator)模式
- 装饰模式(Decorator Pattern)
- 装饰(Decorator)模式
- 装饰模式:Decorator
- 装饰模式(Decorator)
- 装饰模式(Decorator Pattern)
- 装饰模式Decorator
- Decorator 装饰者模式
- 装饰模式(Decorator)
- 装饰模式(Decorator)
- DECORATOR (装饰)模式
- Decorator装饰模式
- 装饰器(Decorator)模式
- 装饰模式(Decorator)
- Decorator(装饰)模式
- 装饰者模式(Decorator)
- 装饰模式Decorator
- [Algorithm & NLP] 文本深度表示模型——word2vec&doc2vec词向量模型
- js改变文本字体大小及颜色,先放大后缩小,10次循环
- 集中式vs分布式
- 1059. C语言竞赛(20) python篇
- (ssl1624)小萨的烦恼
- 装饰模式 Decorator
- android String字符串中提取数字
- 华为S6700系列交换机基础知识
- CMD中monkeyrunner不是外部不是内部的坑
- Java NIO编程实例之三Selector
- 学习JDBC的总结
- bzoj 3473: 字符串 广义后缀自动机
- 1013. 数素数 (20) python篇
- 渗透测试的目标、思路