装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的,至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
本次的场景是在为人物搭配不同的服装。由于只有一个ConcreteComponent类,故而此处直接使用Decorator类直接继承ConcreteDecorator类。代码如下:
Person类(ConcreteDecorator):
package chapter6.version3;
public class Person {
public Person() {}
private String name;
public Person (String name) {
this.name = name;
}
public void show() {
System.out.printf("装扮的%s", name);
}
}
Finery类(Decorator):
package chapter6.version3;
public class Finery extends Person {
protected Person component;
public void decorate(Person component) {
this.component = component;
}
@Override
public void show() {
if (component != null) {
component.show();
}
}
}
具体服饰类(ConcreteDecorator):
package chapter6.version3;
public class TShirts extends Finery {
@Override
public void show() {
System.out.println("大T恤");
super.show();
}
}
package chapter6.version3;
public class BigTrousers extends Finery {
@Override
public void show() {
System.out.println("垮裤");
super.show();
}
}
package chapter6.version3;
public class Tie extends Finery {
@Override
public void show() {
System.out.println("领带");
super.show();
}
}
package chapter6.version3;
public class Sneakers extends Finery {
@Override
public void show() {
System.out.println("破球鞋");
super.show();
}
}
package chapter6.version3;
public class Suit extends Finery {
@Override
public void show() {
System.out.println("西装");
super.show();
}
}
package chapter6.version3;
public class LeatherShoes extends Finery {
public void show() {
System.out.println("皮鞋");
super.show();
}
}
装扮结果类(模拟客户端):
package chapter6.version3;
public class Result {
public void main(String[] args) {
Person xc = new Person("小菜");
System.out.println("第一种装扮:");
Sneakers pqx = new Sneakers();
BigTrousers kk = new BigTrousers();
TShirts dtx = new TShirts();
pqx.decorate(xc);
kk.decorate(pqx);
dtx.decorate(kk);
dtx.show();
System.out.println("第二种装扮");
LeatherShoes px = new LeatherShoes();
Tie ld = new Tie();
Suit xz = new Suit();
px.decorate(xc);
ld.decorate(px);
xz.decorate(ld);
xz.show();
}
}
装饰模式是为已有功能动态地添加更多功能的一种方式。在起初的设计中,当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常修饰了原有类的核心职责或主要行为,这种做法的问题在于,它们在主类中添加了新的字段、新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在特定情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所需要装饰的对象,因此,当需要执行特殊行为时,客户端代码就可以在运行时根据有选择地、按顺序地使用装饰功能包装对象了。
这样做的最大好处是有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。