Java 装饰模式 (Decorator)
来源:互联网 发布:年薪百万知乎 编辑:程序博客网 时间:2024/04/30 14:37
装饰模式
动态的将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的代替方案
代码
package gx.component;/** * 组件:装饰类和被装饰类 都要继承:为了类型保持一致 * @author always * */public abstract class Component { public abstract void description(); public abstract int cost();}
package gx.component.impl;import gx.component.Component;/** * 装饰类的抽象类 * @author always * */public abstract class Decorator extends Component{ protected Component component;}
package gx.component.impl;import gx.component.Component;/** * * 被包装的类 * @author always * */public class Phone extends Component{ public void description() { System.out.println("裸机"); } public int cost() { return 1900; }}
package gx.decorator.impl;import gx.component.Component;import gx.component.impl.Decorator;/** * * 装饰1:给手机买个壳 * @author always * */public class DaiKe extends Decorator{ public DaiKe(){ } public DaiKe(Component component){ this.component=component; } public void description() { this.component.description(); System.out.println("带了手机壳"); } public int cost() { return 50+this.component.cost(); }}
package gx.decorator.impl;import gx.component.Component;import gx.component.impl.Decorator;/** * * 装饰2:给手机贴个膜 * @author always * */public class TieMo extends Decorator{ public TieMo(){} public TieMo(Component component){ this.component=component; } public void description() { this.component.description(); System.out.println("贴了膜"); } public int cost() { return 20+this.component.cost(); }}
测试类:
package gx;import gx.component.Component;import gx.component.impl.Phone;import gx.decorator.impl.DaiKe;import gx.decorator.impl.TieMo;import junit.framework.TestCase;public class TestDecorator extends TestCase { public void testDecorator() { Component component = new TieMo(new DaiKe(new Phone())); component.description(); System.out.println("价钱:" + component.cost()); /* * 结果: * 裸机 * 带了手机壳 * 贴了膜 * 价钱:1970 */ }}
0 0
- Java 装饰模式 (Decorator)
- Java装饰模式(Decorator模式)
- Java设计模式---装饰模式(Decorator)
- Java装饰模式(Decorator模式)
- JAVA设计模式:装饰器(Decorator)
- java中装饰设计模式(decorator)
- Java之装饰模式(Decorator Pattern)
- Java之装饰模式(Decorator Pattern)
- Java之装饰模式(Decorator Pattern)
- 装饰(Decorator)模式
- 装饰模式(Decorator)
- 装饰模式(Decorator)
- DECORATOR (装饰)模式
- Decorator(装饰)模式
- 装饰模式(Decorator)
- Decorator(装饰模式)
- 装饰模式(Decorator)
- 装饰模式(Decorator)
- 黑马程序员--数组的概念
- LeetCode Insert Interval
- 一根网线发起的攻击
- 最短的崩溃程序(C语言版)
- 一对一,多对多映射配置
- Java 装饰模式 (Decorator)
- Struts2基础
- 计算机是如何启动的?
- 个性化配置--Linux Terminal终端
- HTML5学习笔记--Form
- BZOJ-1857-传送带-SCOI2010
- easyui添加自定义图标
- 一款基于jquery带百分比的响应式进度加载条
- c#---类和结构