设计模式之装饰者模式
来源:互联网 发布:阴谋论书籍 知乎 编辑:程序博客网 时间:2024/06/08 13:44
装饰者模式的基本组成是一个目标类和一个继承于(实现了)目标类的装饰基类,目标类可以抽象出基类和多个子类,而装饰基类可以派生出多种具体的装饰类。
目标类中指定了核心行为,装饰基类继承于目标类,装饰基类及其子类通过重写这个行为方法,给目标类添加行为。装饰者模式特殊的一点是装饰类持有的引用,也就是依赖于目标类型,通过在行为方法中调用所依赖目标类型类的方法来实现行为的传承。
目标基类:
public abstract class Person { abstract void wear();}
目标实现类:
public class Man extends Person { @Override void wear() { System.out.print("男人"); }}
装饰基类:持有目标类的引用,本身继承于目标类,重写的行为方法是调用持有目标类的行为方法。
public abstract class DecoratorPerson extends Person { Person person; public DecoratorPerson(Person person) { this.person = person; } @Override void wear() { person.wear(); }}
装饰子类:继承于装饰基类,重写的行为方法是调用持有目标类的行为方法,加上自己添加的行为。
public class TShirtDecorator extends DecoratorPerson { public TShirtDecorator(Person person) { super(person); } @Override void wear() { super.wear(); System.out.print(" 穿T恤"); }}public class PantsDecorator extends DecoratorPerson { public PantsDecorator(Person person) { super(person); } @Override void wear() { super.wear(); System.out.print(" 穿长裤"); }}
测试类:
public class Test { public static void main(String[] args){ Man man = new Man(); TShirtDecorator tShirtDecorator = new TShirtDecorator(man); tShirtDecorator.wear(); System.out.println(); new PantsDecorator(tShirtDecorator).wear(); System.out.println(); new UnderwearDecorator(new ShoesDecorator(new PantsDecorator(new Man()))).wear(); }}
输出结果:
男人 穿T恤男人 穿T恤 穿长裤男人 穿长裤 穿鞋子 穿内裤
装饰者模式就像俄罗斯套娃,可以一层一层包装起来。
Java中的IO类即是使用装饰者模式实现的。
阅读全文
0 0
- 设计模式之装饰者设计模式
- 设计模式 之 装饰者
- 设计模式之装饰者模式
- 设计模式之装饰者模式
- 设计模式之Decorator(装饰者模式)
- 设计模式之五---装饰者模式
- 设计模式之---装饰者模式
- c++设计模式之装饰者模式
- Php设计模式之装饰者模式
- java设计模式之装饰者模式
- 设计模式之装饰者模式
- 【设计模式】之装饰者模式
- HeadFirst设计模式之装饰者模式
- c++设计模式之装饰者模式
- 设计模式之装饰者模式
- 设计模式之--装饰者模式
- 设计模式之装饰者模式
- 设计模式之装饰者模式
- solr配置文件
- wifi能够保护你在虚拟现实中不会丢失
- VS2013相关报错问题
- UVa10763-Foreign Exchange-交换学生--map映射和pair对的使用
- <iOS读书笔记>之Objective-C高级编程(GCD)
- 设计模式之装饰者模式
- 上传文件
- 32day 新浪微博(授权 新特性)
- datacleaner第一部分,一、二、三章
- 欢迎使用CSDN-markdown编辑器
- 20170801_动态规划之爬楼梯有多少不同的方法
- 归并排序
- java 代理模式
- 游戏开发中的人工智能(十四):神经网络