原文地址:http://leihuang.org/2014/12/09/decorator/
Structural 模式 如何设计物件之间的静态结构,如何完成物件之间的继承、实 现与依赖关系,这关乎着系统设计出来是否健壮(robust):像是易懂、易维护、易修改、耦合度低等等议题。Structural 模式正如其名,其分类下的模式给出了在不同场合下所适用的各种物件关系结构。
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。
装饰模式的类图如下:

在装饰模式中的角色有:
例如我们现在要装饰一棵圣诞树,要有一棵简单树,和一些装饰材料,如灯光,圣诞帽,气球等.下面就是类结构图.

ITree 接口
public interface ITree {
    public void decorate() ;
}
SimpleTree 一棵光秃秃的树
public class SimpleTree implements ITree {
    private int height,width ;
    public SimpleTree(int height,int width){
        this.height = height ;
        this.width = width ;
    }
    @Override
    public void decorate() {
        System.out.println("tree's height="+height+" width="+width);
    }
}
Decorator 装饰抽象类
public abstract class Decorator implements ITree {
    private ITree tree = null ;
    public Decorator(ITree tree){
        this.tree = tree ;
    }
    @Override
    public void decorate() {
        tree.decorate();
    }
}
Light 装饰材料灯光
public class Light extends Decorator {
    public Light(ITree tree) {
        super(tree);
    }
    @Override
    public void decorate() {
        super.decorate();
        System.out.println("装有灯光!");
    }
}
Cat 装饰材料,圣诞帽
public class Cat extends Decorator {
    public Cat(ITree tree) {
        super(tree);
    }
    public void decorate(){
        super.decorate();
        System.out.println("装有圣诞帽!");
    }
}
Balloon 装饰材料,气球
public class Balloon extends Decorator {
    public Balloon(ITree tree) {
        super(tree);
    }
    public void decorate(){
        super.decorate();
        System.out.println("装有气球!");
    }
}
Client 客户端
public class Client {
    public static void main(String[] args) {
        ITree tree = new SimpleTree(10, 10) ;
        Decorator tree_light = new Light(tree) ;
        tree_light.decorate();
        Decorator tree_light_cat = new Cat(tree_light) ;
        tree_light_cat.decorate();
        Decorator tree_light_cat_Balloon = new Balloon(tree_light_cat) ;
        tree_light_cat_Balloon.decorate();
        /*tree's height=10 width=10
        装有灯光!
        tree's height=10 width=10
        装有灯光!
        装有圣诞帽!
        tree's height=10 width=10
        装有灯光!
        装有圣诞帽!
        装有气球!*/
    }
}
2014-12-09 20:26:30
Brave,Happy,Thanksgiving !
原文地址:http://blog.csdn.net/speedme/article/details/41869787