装饰者模式

装饰者模式通过组合的方式来扩展对象的行为,而不依赖于继承,也就是说虽然类的框架中包含继承,但只是为了获取正确的类型,而不是继承一种行为。行为来自于装饰者和基础组件,或者与其他装饰者之间的组合关系。

装饰者模式描述:采用组合的方式将多个同类对象任意搭配组成一个对象,达到增强效果。比如java中的IO用到了装饰者模式模式。

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

实现:

// 对衣服进行抽象
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());
    }
}
输出结果:衣服的组成部分:衬衫,花儿,泰迪熊
在这里我要说说
tedFlowerShirt.description()这段代码的执行过程。
他是按照
new TedBearDecorator(new FlowerDecorator(new Shirt()))这段代码的外层向里面调用的,然后从里面向外面输出结果的。
首先调用
TedBearDecorator.description(),然后调用FlowerDecorator.description(),最后调用Shirt.description()。返回就是逆向返回。

原文地址:https://www.cnblogs.com/xubiao/p/5475875.html