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

在装饰模式中的角色有:
- 抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
- 具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。
- 装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
- 具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。
例如我们现在要装饰一棵圣诞树,要有一棵简单树,和一些装饰材料,如灯光,圣诞帽,气球等.下面就是类结构图.

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 !
装饰模式是一种结构型设计模式,它允许在不修改对象本身的情况下,通过添加额外的职责来扩展对象功能。文章通过类图解释了抽象构件、具体构件、装饰和具体装饰的角色,并举例说明了装饰一棵圣诞树的过程,展示了如何使用装饰模式添加灯光、圣诞帽和气球等装饰材料。
1407

被折叠的 条评论
为什么被折叠?



