前言
在开发过程中,我们会遇到要将某一个功能赋予额外的职责,并把这些增加了额外职责的功能按照正确的顺序串联起来进行控制,且可以灵活地调换这些顺序,输出最后执行的结果,装饰模式就是这样一个非常有意思的设计模式。
场景
衣服、鞋子、领带、披风都可以理解为对人的装饰。而且可以选择先穿衣服再穿鞋子,或者先穿鞋子,再穿衣服
策略模式
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
代码示例
Person类(ConcreteComponent)
public class Person {
private String name;
public Person(){}
public Person(String name){
this.name = name;
}
public void show(){
System.out.println("装扮的" + name);
}
}
服饰类(Decorator)
public class Finery extends Person{
protected Person component;
/**
* 打扮
*
* @param component
*/
public void decorate(Person component){
this.component = component;
}
@Override
public void show(){
if (null != component){
component.show();
}
}
}
具体服饰类(ConcreteDecorator)
public class TShirts extends Finery {
@Override
public void show(){
System.out.println("大T恤");
super.show();
}
}
public class BigTrouser extends Finery {
@Override
public void show(){
System.out.println("垮裤");
super.show();
}
}
//其余类类似,省略
..........
客户端
public class Main {
public static void main(String[] args) {
Person person = new Person("Java_Mike");
System.out.println("第一种装扮");
Sneakers sneakers = new Sneakers();
BigTrouser bigTrouser = new BigTrouser();
TShirts tShirts = new TShirts();
sneakers.decorate(person);
bigTrouser.decorate(sneakers);
tShirts.decorate(bigTrouser);
tShirts.show();
System.out.println("第二种装扮");
LeatherShoes leatherShoes = new LeatherShoes();
Tie tie = new Tie();
Suit suit = new Suit();
leatherShoes.decorate(person);
tie.decorate(leatherShoes);
suit.decorate(tie);
suit.show();
}
}
运行结果
优点
- 把类中的装饰功能从类中搬移去除,这样可以简化原有的类
- 有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。
参考资料
[1]: 大话设计模式 程杰著 清华大学出版社
[2]: https://blog.youkuaiyun.com/wwwdc1012/article/details/82764333