• 装饰者模式


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

    装饰者模式描述:采用组合的方式将多个同类对象任意搭配组成一个对象,达到增强效果。比如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()。返回就是逆向返回。

  • 相关阅读:
    .Net Core 第三方工具包整理
    .Net Core 读取appsettings.json的配置
    .Net Core 常见问题整理
    .Net Core 学习资料
    LVM使用
    PIP本地源搭建
    sed命令使用
    Shell脚本
    SNAT端口转发配置
    Ubuntu软件包管理
  • 原文地址:https://www.cnblogs.com/xubiao/p/5475875.html
Copyright © 2020-2023  润新知