一、装饰者模式
装饰者模式是为已有功能动态地增加更多功能的一种方式。
待解决的问题:当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。这种方式的缺点是在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。而新加入的东西仅仅是为了满足一些只在某些特定情况下才会执行的特殊需要。
装饰者模式:把每个要装饰的功能放在单独的类中,并让这个类包装它要装饰的对象。因此,当需要执行特殊行为时,客户代码就可以在运行时,根据需要有选择地、按顺序地使用装饰功能包装对象。
二、UML类图
如下图所示,Component为抽象类,具体对象类和装饰抽象类都继承了该类,具体对象类为待动态增加功能的对象,装饰抽象类内有一个成员变量,为Component类,运行时指向具体对象类或具体装饰类。
三、具体案例
引用大话设计模式案例-小菜扮靓,为小菜搭配衣服,如穿T恤和垮裤,或者是穿西装和打领带,且这些搭配的穿法是有一定顺序,如先穿西装再打领带。抽象成装饰模式,小菜为待装饰的对象,穿T恤、垮裤、西装、领带为具体装饰类。
具体实现的java代码:
public class DecoratorDesign {
public static void main(String[] args) {
Person person=new Person();
TShirts tShirts=new TShirts();
BigTrouser bigTrouser=new BigTrouser();
Suit suit=new Suit();
Tie tie=new Tie();
//第一种装饰
System.out.println("第一种装饰:");
tShirts.setComponent(person);
bigTrouser.setComponent(tShirts);
bigTrouser.show();
//第二种装饰
System.out.println("第二种装饰:");
suit.setComponent(person);
tie.setComponent(suit);
tie.show();
}
}
//Component类,因为只有一个Person的子类,所以将Component和ConcoreteComponent合并为一个类
class Person{
public void show(){
System.out.println("person show");
}
}
//继承Component的装饰类,包含成员变量Component
abstract class Decorator extends Person{
Person person;
public void setComponent(Person person) {
this.person=person;
}
public void show(){
if(person!=null)
person.show();
}
}
//具体的装饰类,先执行主要功能,再执行装饰功能
class TShirts extends Decorator{
public void show(){
super.show();
System.out.println("大T恤");
}
}
class BigTrouser extends Decorator{
public void show(){
super.show();
System.out.println("垮裤");
}
}
class Suit extends Decorator{
public void show(){
super.show();
System.out.println("西装");
}
}
class Tie extends Decorator{
public void show(){
super.show();
System.out.println("领带");
}
}
实现结果:
第一种装饰: person show 大T恤 垮裤 第二种装饰: person show 西装 领带 |
参考:大话设计模式