20230419 6. 装饰模式 - 衣服搭配

发布时间 2023-06-19 09:46:21作者: 流星<。)#)))≦

介绍

需要把所需的功能按正确的顺序串联起来进行控制

建造者模式要求建造的过程必须是稳定的,而现在我们这个例子,建造过程是不稳定的

装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

装饰模式

  • Component 是定义一个对象接口,可以给这些对象动态地添加职责。
  • ConcreteComponent 是定义了一个具体的对象,也可以给这个对象添加一些职责。
  • Decorator 装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无须知道Decorator的存在的。
  • ConcreteDecorator 就是具体的装饰对象,起到给Component添加职责的功能

装饰模式是利用SetComponent来对对象进行包装的。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中

学习模式要善于变通,如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

装饰模式是为已有功能动态地添加更多功能的一种方式

当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,比如用西装或嘻哈服来装饰小菜,但这种做法的问题在于,它们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了

装饰模式的优点是,把类中的装饰功能从类中搬移去除,这样可以简化原有的类,这样做更大的好处就是有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑

代码示例

Component

public interface ICharacter {
    void show();
}

ConcreteComponent

public class Person implements ICharacter{
    @Override
    public void show() {
        System.out.println(" 装扮的人");
    }
}

Decorator

public class Finery implements ICharacter {

    private ICharacter character;

    public Finery(ICharacter character) {
        this.character = character;
    }

    @Override
    public void show() {
        character.show();
    }
}

ConcreteDecorator

public class Suit extends Finery{
    public Suit(ICharacter character) {
        super(character);
    }

    @Override
    public void show() {
        System.out.print(" 套装 ");
        super.show();
    }
}

public class Tie extends Finery {

    public Tie(ICharacter character) {
        super(character);
    }

    public void show() {
        System.out.print(" 领带");
        super.show();
    }

}

public class TShirts extends Finery {
    public TShirts(ICharacter character) {
        super(character);
    }

    @Override
    public void show() {
        System.out.print(" T恤 ");
        super.show();
    }
}

客户端

public class Test {
    public static void main(String[] args) {
        Person person = new Person();
        person.show();

        System.out.println("====================");
        TShirts tShirts = new TShirts(person);
        tShirts.show();

        System.out.println("====================");
        Suit suit = new Suit(tShirts);
        suit.show();

        System.out.println("====================");
        Tie tie = new Tie(tShirts);
        tie.show();

    }
}

将收银-策略模式,修改为收银-装饰模式

收银-装饰模式