HeadFirst 设计模式中对装饰者模式的定义:
装饰者模式动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更具有弹性的替代方案。
以下是HeadFirst 设计模式中关于装饰者模式的类图:
1、有一个抽象的组件(面条)。
2、有具体的组件实现(牛肉面、鸡蛋面)。
3、有进行装饰的类(加鸡蛋、加香肠,并且持有组件)。
示例代码如下:
组件基类(面条)
package iodemo;/** * * 面条基类 */public abstract class Noodle { public abstract int cost();}
组件实现(牛肉面、鸡蛋面)
package iodemo;/** * 牛肉面(一种具体的面条) * */public class NiuRouNoodle extends Noodle { @Override public int cost() { System.out.println("牛肉面5元一碗"); return 5; }}
package iodemo;/** * 刀削面(一种具体的面条) * */public class DaoXiaoNoodle extends Noodle { @Override public int cost() { System.out.println("刀削面3元一碗"); return 3; }}
进行装饰的类(加鸡蛋、加香肠,并且持有组件)
package iodemo;/** * 加鸡蛋(装饰)类,继承面条基类,对面条的方法进行包装,并且持有面条的引用 * */public class JiDanDecoratorNoodle extends Noodle { private Noodle noodle; public JiDanDecoratorNoodle(Noodle noodle) { this.noodle = noodle; } @Override public int cost() { System.out.println("加鸡蛋1元"); return this.noodle.cost() + 1; }}
package iodemo;/** * 加(装饰)类,继承面条基类,对面条的方法进行包装,并且持有面条的引用 * * @author Administrator * */public class XiangChangDecoratorNoodle extends Noodle { private Noodle noodle; public XiangChangDecoratorNoodle(Noodle noodle) { this.noodle = noodle; } @Override public int cost() { System.out.println("加香肠2元"); return this.noodle.cost() + 2; }}
测试类
package iodemo;public class Test { public static void main(String[] args) { //低配版牛肉面 NiuRouNoodle niuRouNoodle=new NiuRouNoodle(); System.out.println(niuRouNoodle.cost()); System.out.println("***************"); //中配版牛肉面(加鸡蛋) JiDanDecoratorNoodle jiDanDecoratorNoodle=new JiDanDecoratorNoodle(niuRouNoodle); System.out.println(jiDanDecoratorNoodle.cost()); System.out.println("***************"); //顶配版牛肉面(加鸡蛋加香肠) XiangChangDecoratorNoodle xiangChangDecoratorNoodle=new XiangChangDecoratorNoodle(jiDanDecoratorNoodle); System.out.println(xiangChangDecoratorNoodle.cost()); }}
运行结果如下:
牛肉面5元一碗
5***************加鸡蛋1元牛肉面5元一碗6***************加香肠2元加鸡蛋1元牛肉面5元一碗8