设计模式:装饰模式
来源:互联网 发布:python win32教程 编辑:程序博客网 时间:2024/04/27 23:56
设计模式:装饰模式
设计模式:装饰模式
装饰模式是对对象功能增强时,平时使用继承的一种替代方案
一.UML示意图:
二.组成部分:
1. 抽象构件:原始的功能接口2. 具体构件:具体的原始功能类3. 装饰角色:持有具体构件类的对象,以便执行原有功能4. 具体装饰:具体扩展的功能在这里
三.例子代码:使用装饰模式来演示一个对”行走”功能扩展的例子(听音乐+行走和唱歌+行走)
1. 抽象构件package com.eekq.decorator;public interface Component {/**原始接口*/publicvoid go();}2. 具体构件package com.eekq.decorator;public class ConcreteComponentimplements Component {publicvoid go() {System.out.println("行走");}}3.装饰角色来了package com.eekq.decorator;public class Decoratorimplements Component {/**持有私有的原始构件*/private Componentcomponent;/**构造函数,委派给原始构件*/protected Decorator(Component component) {this.component = component;}/**调用原始构件功能,通常就可直接把扩展功能加在此方法中*/publicvoid go() {this.component.go();}}4.具体装饰(这里演示了两种扩展的情况,走路+听音乐和唱歌s)(1).package com.eekq.decorator;public class ConcreteDecoratorListenextends Decorator {/**构造函数,相关初始化*/public ConcreteDecoratorListen(Component component) {super(component);// code is here}/**商业逻辑,对原始构件功能的扩展*/publicvoid go() {listen("听音乐");//执行扩展功能super.go();}privatevoid listen(Object obj){System.out.println(obj);}}(2).package com.eekq.decorator;publi cclass ConcreteDecoratorSingextends Decorator {/**构造子,相关初始化*/public ConcreteDecoratorSing(Component component) {super(component);// code is here}/**商业逻辑,对原始构件功能的扩展*/publicvoid go() {super.go();System.out.println(sing());;// 执行扩展功能}private String sing() {return"唱歌";}}5.客户端调用package com.eekq.decorator;publicclass Main {publicstaticvoid main(String[] args) {/**原始构件*/Component component = new ConcreteComponent();/**边听音乐,边走路*/ConcreteDecoratorListen cdl =new ConcreteDecoratorListen(component);cdl.go();System.out.println();/**边走路,边唱歌*/ConcreteDecoratorSing cds =new ConcreteDecoratorSing(component);cds.go();}}
四.总结
优点:装饰模式和继承都是对功能的扩展,而装饰模式使用的是组合,可以不用继承而达到这一效果.使用过多的继承会增加系统的复杂性和偶合性。缺点:装饰模式要产生一些辅助性的对象,但这些对象看上去都比较像,不是很容易检查(好的命名应该是提高检查的一个办法)。
- 设计模式---装饰模式
- 设计模式:装饰模式
- 设计模式------装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式 装饰模式
- 设计模式----装饰模式
- 设计模式-【装饰模式】
- 设计模式--装饰模式
- 设计模式装饰模式
- 设计模式 - 装饰模式
- 设计模式-----装饰模式.
- 设计模式-----装饰模式.
- [ 设计模式 ] 装饰模式!
- 设计模式:装饰模式
- 设计模式 - 装饰模式
- 设计模式 - 装饰模式
- Mono在国内的发展历程(相关文章汇总)
- errno多线程安全
- 判断gps是否开启
- c++头文件和实现文件应该怎么布置
- solr查询参数使用说明
- 设计模式:装饰模式
- .net 与 java 互调webservice 时注意的问题
- mysql学习之--7、select查询详解
- web项目建立——tomcat
- 使用 Apache Solr 实现更加灵巧的搜索,第 1 部分: 基本特性和 Solr 模式
- 栈溢出:strcpy()造成的缓冲区溢出
- mapreduce 利用InverseMapper.class对key,value进行 交换实现词频排序 .
- errno与多线程
- C#代理delegata学习