装饰模式(包装器):动态地为对象添加一些额外的职责。
装饰模式是动态地扩展一个对象的功能,而不需要改变原始类代码。
装饰模式主要包括四种角色:
1、抽象组件(Component):定义了“被装饰者”需要进行装饰的方法。
2、具体组件(ConcreteComponent):抽象组件的子类,具体组件实例也称为“被装饰者”
3、装饰(Decorator):也是抽象组件的子类,还包含了抽象子组件变量,该类的实例称为“装饰者”。
4、具体装饰者(ConcreteDecorator):是装饰者的一个非抽象子类,该类的实例称为“装饰者”。
装饰者的类图:
例子说明:
现有一只麻雀能够飞行100M,假如想让麻雀能够飞行到150M,又不修改麻雀类代码,通过给麻雀安装一对电子翅膀,让麻雀能够飞行所要求的距离。
/** * */ package org.rico.pattern.demo.decorator; /** * @author rico 2013-3-10 * 抽象组件 */ public abstract class Bird { public abstract int fly(); }
/** * */ package org.rico.pattern.demo.decorator; /** * @author rico 2013-3-10 * 具体组件 */ public class Sparrow extends Bird { public static final int DISTANCE = 100; public Sparrow() {} /* (non-Javadoc) * @see org.rico.pattern.demo.decorator.Bird#fly() */ @Override public int fly() { return DISTANCE; } }
/** * */ package org.rico.pattern.demo.decorator; /** * @author rico 2013-3-10 * 装饰器 */ public abstract class Decorator extends Bird { protected Bird bird; public Decorator() {} public Decorator(Bird bird) { this.bird = bird; } }
/** * */ package org.rico.pattern.demo.decorator; /** * @author rico 2013-3-10 * 具体装饰器 */ public class SparrowDecorator extends Decorator { public static final int DISTANCE = 50; public SparrowDecorator(Bird bird) { super(bird); } /* (non-Javadoc) * @see org.rico.pattern.demo.decorator.Bird#fly() */ @Override public int fly() { return bird.fly()+extFly(); //开挂,让麻雀能多50 } //装饰器新增方法 private int extFly() { return DISTANCE; } }
/** * */ package org.rico.pattern.demo.decorator; /** * @author rico 2013-3-10 * */ public class test { /** * @param args */ public static void main(String[] args) { Bird bird = new Sparrow(); //能飞100米的麻雀 Decorator decoratorOne = new SparrowDecorator(bird); //能飞150米的麻雀 Decorator decoratorTwo = new SparrowDecorator(decoratorOne);//能飞200米的麻雀 System.out.println("######################################"); System.out.println("####decoratorOne: " + decoratorOne.fly() + "####decoratorTwo: " + decoratorTwo.fly()); System.out.println("######################################"); } }
相关推荐
设计模式 - 装饰模式(C++实例) 若有问题,请指出。
设计模式--装饰者模式java例子
设计模式--装饰模式 设计模式--装饰模式 设计模式--装饰模式 设计模式--装饰模式
23种设计模式--装饰模式
JAVA-设计模式-结构型模式-装饰模式
c++设计模式-结构型模式-装饰器模式;QT工程;c++简单源码; 装饰器(Decorator)模式的定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。
设计模式-装饰模式(讲解及其实现代码)
设计模式 - 装饰者模式
2.开发一个系统帮助业务部门实现灵活的奖金计算。对于普通员工,主要有个人当月业务奖金、个人当月回款奖金等,对于部门经理,除了有普通员工的奖金外,还有...请写出你所选择的设计模式,画出类图,并给出核心代码。
java常用设计模式-装饰器模式
设计模式专题之(七)装饰模式---设计模式装饰模式示例代码(python--c++)
设计模式—装饰者模式,介绍的非常详细,讲解透彻
cpp代码-设计模式-装饰模式
本章可以称为“给爱用继承的人一个全新的设计眼界”。我们即将再度探讨典型滥用问题。你将在本章学到如何使用对象组合的方式,做到在运行时装饰类。为什么呢?一旦你熟悉了装饰者的技巧...——《Head First 设计模式》
ios平台中通过最简单的代码讲解装饰器模式,可在博客http://blog.sina.com.cn/s/blog_161d504630102wxis.html中查看简单解释
使用PHP实现的设计模式之装饰者模式,希望对您的开发有所启发。
装饰者模式:动态地将责任附加到对象上,若要扩展对象,装饰者模式提供了比继承更弹性的替代方案