GoF23种设计模式之结构型模式之装饰模式

一、概述

        动态地给一个对象添加一些额外的职责。装饰模式比生成子类更为灵活。

二、适用性

1.在不影响其他对象的情况下,以动态、透明的方式给但个对象添加职责。

2.处理那些可以撤销的职责。

3.当不能采用生成子类的方式进行扩展的时候。

三、参与者

1.Component:定义一个对象接口,可以给这些对象动态地添加职责。

2.ConcreteComponent:定义一个对象,可以给这个对象添加一些职责。

3.Decorator:维持一个指向Component对象的指针,并且定义一个与Component接口一致的接口。

4.ConcreteDecorator:向组件添加职责。

四、类图


五、示例

Component

package cn.lynn.decorator;

public interface IAnimal {

    public void eat();

}
ConcreteComponent

package cn.lynn.decorator;

public class Dog implements IAnimal {

    @Override
    public void eat() {
        System.out.println("狗啃骨头!");
    }

}
Decorator

package cn.lynn.decorator;

public abstract class Decorator implements IAnimal {
    private IAnimal animal;

    public void setAnimal(IAnimal animal) {
        this.animal = animal;
    }

    @Override
    public void eat() {
        animal.eat();
    }

}
ConcreteDecorator

package cn.lynn.decorator;

public class DogDecoratorA extends Decorator {

    @Override
    public void eat() {
        super.eat();
        transform();
    }
    
    public void transform() {
        System.out.println("机器狗变形出发!");
    }
}
package cn.lynn.decorator;

public class DogDecoratorB extends Decorator {

    @Override
    public void eat() {
        super.eat();
        say();
    }
    
    public void say() {
        System.out.println("旺旺!");
    }
}
Client

package cn.lynn.decorator;

public class Client {

    public static void main(String[] args) {
        Dog dog = new Dog();
        DogDecoratorA dogDecoratorA = new DogDecoratorA();
        DogDecoratorB dogDecoratorB = new DogDecoratorB();
        dogDecoratorA.setAnimal(dog);
        dogDecoratorB.setAnimal(dogDecoratorA);
        dogDecoratorB.eat();
    }

}
Result

狗啃骨头!
机器狗变形出发!
旺旺!

原文地址:https://www.cnblogs.com/innosight/p/3271149.html