装饰则模式
来源:互联网 发布:算法导论22.3 13 编辑:程序博客网 时间:2024/06/08 08:08
概念:动态的为对象增加额外的职责,比生成子类更为灵活。
实例中,Component ConcreteComponent都为Person。
//公共接口,也是目标类,职责的承受者public interface Person { void eat();}//装饰者类,负责生成职责public abstract class Decorator implements Person { protected Person person; public void setPerson(Person person) { this.person = person; } public void eat() { person.eat(); }}//具体职责Apublic class ManDecoratorA extends Decorator { public void eat() { super.eat(); reEat(); System.out.println("ManDecoratorA类"); } public void reEat() { System.out.println("再吃一顿饭"); }}//具体职责B class ManDecoratorB extends Decorator { public void eat() { super.eat(); System.out.println("吃成猪"); System.out.println("ManDecoratorB类"); } } //具体职责C class ManDecoratorC extends Decorator { public void eat() { super.eat(); System.out.println("吃前祈祷"); System.out.println("ManDecoratorC类"); }//调用public static void main(String[] args) { Man man = new Man(); ManDecoratorC md3 = new ManDecoratorC(); ManDecoratorA md1 = new ManDecoratorA(); ManDecoratorB md2 = new ManDecoratorB(); //先设置父类中 Person 的具体实现 ,在执行eat方法时。 super.eat();都是先执行父类的eat(),也就是 //具体传入的实现, /** * 执行第一条前,父类中 Person为Man,父类执行的eat()就是Man的eat() */ md3.setPerson(man); /** * 执行第二条前,父类中 Person为Man3,父类执行的eat()就是Man3的eat() */ md1.setPerson(md3); /** * 执行第三条前,父类中 Person为Man1,父类执行的eat()就是Man1的eat() */ md2.setPerson(md1); /** * 执行第四条前,先执行父类的eat(),在执行本类。md2的父类eat()为eat1(),md1的父类eat()为eat3(), * ,md3的父类eat()为具体实现的eat() */ md2.eat(); }
阅读全文
0 0
- 装饰则模式
- 装饰模式-撤销装饰
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 阿里云幸运券的使用规则及领用方法
- js实用工具方法及小技巧
- linux 基础10
- //利用 DirectoryInfo递归遍历文件夹,删除所有文件,文件夹
- Linux——网络
- 装饰则模式
- Firebug及YSlow简介与使用图文详解
- Linux中文件搜索命令介绍
- mac谷歌浏览器实现跨域
- springmvc拦截请求
- python(6) 类/私有变量/多态
- 多maven工程依赖写法注意问题
- 腾讯2017秋招笔试编程题(三)---素数对
- 安装Java JDK