装饰者模式

907 查看

描述:采用组合的方式将多个同类对象任意搭配组成一个对象,达到增强效果

场景:比如一件衣服如果只是一件衬衫,那么太单调了,如果在这衣服上加上泰迪熊、花儿,那么这件衣服就特有喜感了(相当于衣服的功能加强了,可以让人笑了)。

实现:

// 对衣服进行抽象
abstract class Clothes {
    abstract String description();
}
// 有一件衬衫
class Shirt extends Clothes {
    @Override
    String description() {
        return "衬衫";
    }
}
// 给衣服装饰一些饰品,对饰品进行抽象
abstract class Decorator extends Clothes {
    Clothes clothes;
    Decorator(Clothes clothes) {
        this.clothes = clothes;
    }
}
// 在衣服上加一个泰迪熊
class TedBearDecorator extends Decorator {
    TedBearDecorator(Clothes clothes) {
        super(clothes);
    }
    @Override
    String description() {
        return this.clothes.description() + "," + "泰迪熊";
    }
}
//在衣服上加一朵花
class FlowerDecorator extends Decorator {
    FlowerDecorator(Clothes clothes) {
        super(clothes);
    }
    @Override
    String description() {
        return this.clothes.description() + "," + "花儿";
    }
}
// 实现一个装饰有泰迪熊、花儿的衬衫
public class DecoratorDemo {
    public static void main(String[] args) {
        // 这个写法是不是让你想起什么
        Clothes tedFlowerShirt = new TedBearDecorator(new FlowerDecorator(new Shirt()));
        // 一件带花儿、泰迪熊的衬衫出来了
        System.out.println("衣服的组成部分:" + tedFlowerShirt.description());
    }
}