设计模式——装饰模式
来源:互联网 发布:js随机数1到22 编辑:程序博客网 时间:2024/06/17 17:44
装饰模式
装饰模式
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
如同我们人要传衣服一样,每天可以穿的衣服有很多,我们可以任意选择几件衣服穿在自己身上,不喜欢也可以随时替换掉身上的衣服。衣服就好比额外的外形修饰,它们可以一层一层穿在我们身上,对我们的外在起到一定的装饰作用。
装饰模式结构图
其中:
1.Component(被装饰对象的基类) 定义一个对象接口,可以给这些对象动态地添加职责。
2.ConcreteComponent(具体被装饰对象)定义一个对象,可以给这个对象添加一些职责。
3.Decorator(装饰者抽象类)维持一个指向Component实例的引用,并定义一个与Component接口一致的接口。
4.ConcreteDecorator(具体装饰者) 具体的装饰对象,给内部持有的具体被装饰对象,增加具体的职责。
具体代码如下:
public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void show() { System.out.println( name + "的穿衣搭配"); }}public class TShirtDecorate extends Person { private Person component; public TShirtDecorate(Person component) { this.component = component; } @Override public void show() { System.out.println("穿T-shirt"); component.show(); }}public class JeanDecorate extends Person { private Person component; public JeanDecorate(Person component) { this.component = component; } @Override public void show() { System.out.println("穿牛仔裤"); component.show(); }}public class CoatDecorate extends Person { private Person component; public CoatDecorate(Person component) { this.component = component; } @Override public void show() { System.out.println("穿外套"); component.show(); }}public class Test { public static void main(String[] args) { Person p = new Person(); p.setName("小菜"); CoatDecorate coatDecorate = new CoatDecorate(new JeanDecorate(new TShirtDecorate(p))); coatDecorate.show(); }}
代码中:
Person类就是ConcreteComponent(被装饰类的具体实现类)
CoatDecorate 等类就是ConcreteDecorator(具体装饰者)
总结:
装饰模式的有点就是把类中的装饰功能从类中搬移去除,这样就可以简化原有的类。有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。
阅读全文
0 0
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式——装饰设计模式
- 设计模式——装饰设计模式
- 设计模式——装饰设计模式
- 【设计模式】——Decorator装饰模式
- 每日设计模式——装饰模式
- 设计模式——装饰者模式
- 设计模式——装饰模式
- 设计模式——装饰模式
- java设计模式——装饰模式
- 设计模式——装饰者模式
- 大话设计模式——装饰模式
- 设计模式——装饰模式
- 设计模式——装饰者模式
- Win7 安装VS2010, .net framework 4.0 失败,错误HRESULT 0xc8000222解决办法
- Linux中遇到问题时常用命令
- SQL SERVER 数据库备份压缩机制
- 【JAVA】Properties文件以及XML文件的读取操作
- 几种常用的设计模式代码
- 设计模式——装饰模式
- codeforces 411div2-fake NP
- 10. Regular Expression Matching
- 配置_eclipse:项目在myeclipse与eclipse之间迁移
- 9-const和volatile分析
- Coscos2d初学的一些知识点01
- 解决linux服务器CentOS(6和7版本),/etc/sysconfig/下没有iptables的问题
- log4j2打印Mybatis执行的SQL语句及SQL语句的执行时间
- Android 贝塞尔曲线自定义波浪