概念
什么是装饰者模式?
动态的给一个对象添加额外的职责或功能。在添加一种额外职责或功能的时候并不修改该对象的类,满足了开闭原则。大致类图如下
代码实现
案例场景
假如我们需要给一个人进行装扮,例如穿什么衣服、裤子、鞋子等。如果我们需要做到能够随意的给人进行搭配,那么改怎样通过代码实现呢?这时候就可以用到装饰者模式。具体代码如下:
Component类
public abstract class PersonComponent {
public abstract void show();
}
ConcreteComponent类
public class Student extends PersonComponent{
private String mName;
public Student(String name){
this.mName = name;
}
@Override
public void show() {
System.out.println(this.mName+"穿的是: ");
}
}
Decorator类
public abstract class BaseDecorator extends PersonComponent{
protected PersonComponent mComponent;
public BaseDecorator(PersonComponent component){
this.mComponent = component;
}
}
ConcreteDecoratorA
public class TShirts extends BaseDecorator{
public TShirts(PersonComponent component) {
super(component);
}
@Override
public void show() {
this.mComponent.show();
System.out.println("T 恤");
}
}
ConcreteDecoratorB
public class Cowboy extends BaseDecorator{
public Cowboy(PersonComponent component) {
super(component);
}
@Override
public void show() {
this.mComponent.show();
System.out.println("牛仔");
}
}
客户端代码
public class TestMain {
public static void main(String[] args){
PersonComponent studentA = new Student("张山");
TShirts tShirtsA = new TShirts(studentA);
Cowboy cowboyA = new Cowboy(tShirtsA);
cowboyA.show();
PersonComponent studentB = new Student("李四");
TShirts tShirtsB = new TShirts(studentB);
tShirtsB.show();
}
}
输出:
张山说我穿的是:
T 恤
牛仔
李四说我穿的是:
T 恤
总结
1、装饰者模式它可以很好的做到为已有的功能动态的添加更多功能,并满足开闭原则;
2、把类中的装饰功能从类中搬除,很好的简化了原来的类。
参考文献
《大话设计模式》
https://blog.csdn.net/gdutxiaoxu/article/details/51885105