这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
为了避免子类数量的快速膨胀,我们可以用装饰模式为对象动态的增加功能。
这些功能应该是没有相互关联和先后顺序的。
举例来说,一个人可以穿各种不同的装扮,如果为每套打扮生成一个子类,那么子类的数量将爆炸。
可以将装饰模式应用进来,使用衣物装饰人。
来看UML图:
Component类是公共基类,定义了show方法。
Person类继承Component类,实现show方法。
Cloth对象将Component类作为其实例变量。
Trouser和TShirts类实现了show方法。

来看具体代码:
public abstract class Component {
public abstract void show();
}
Component定义一个虚方法。
public class Person extends Component {
private String name = null;
public Person(String name) {
this.name = name;
}
public void show() {
System.out.println("我是" + name);
}
}
Person实现了这个虚方法。
public class Cloth extends Component {
protected Component component = null;
public Cloth(pers.zcy.decorator.Component component) {
super();
this.component = component;
}
@Override
public void show() {
if(component != null){
component.show();
}
}
}
Cloth类是装饰器的基类,其中包含一个Component实例对象,在show中调用这个实例对象的show方法。
public class Trouser extends Cloth {
public Trouser(Component component) {
super(component);
// TODO Auto-generated constructor stub
}
@Override
public void show(){
super.show();
System.out.println("我穿了裤子");
}
}
public class TShirts extends Cloth {
public TShirts(Component component) {
super(component);
}
@Override
public void show(){
super.show();
System.out.println("我穿了T恤");
}
}
这两个类重写show方法,同时显式调用父类方法。
public class DecoratorDemo {
public static void main(String[] args) {
Person person = new Person("Mike");
Cloth tshirts = new TShirts(person);
Cloth trousers = new Trouser(tshirts);
trousers.show();
}
}
原文:http://www.cnblogs.com/zcy-backend/p/6670652.html