zoukankan      html  css  js  c++  java
  • Java装饰者模式

    1 什么是装饰者模式

    装饰者模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰者来包裹真实的对象。

    所以装饰者可以动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的方案。

    2 装饰者模式组成结构

        抽象构件 (Component):给出抽象接口或抽象类,以规范准备接收附加功能的对象。
        具体构件 (ConcreteComponent):定义将要接收附加功能的类。
        抽象装饰 (Decorator):装饰者共同要实现的接口,也可以是抽象类。
        具体装饰 (ConcreteDecorator):持有一个 Component 对象,负责给构件对象“贴上”附加的功能。

    3 装饰者模式 UML 图解

    代码示例:

    abstract class Coffe {
        public String coffeBean = "咖啡豆";
    
        public String getCoffeBean() {
            return coffeBean;
        }
    
        public abstract double getPrice();
    }
    
    class LatteCoffee extends Coffe {
        public LatteCoffee() {
            coffeBean = "Latte";
        }
    
        @Override
        public double getPrice() {
            return 31.05;
        }
    }
    
    
    abstract class Starbuk extends Coffe {
        @Override
        public abstract String getCoffeBean();
    }
    
    class VanillaLatte extends Starbuk {
        private Coffe coffe = null;
    
        public VanillaLatte(Coffe coffe) {
            this.coffe = coffe;
        }
    
        @Override
        public String getCoffeBean() {
            return "香草拿铁";
        }
    
        @Override
        public double getPrice() {
            return 3 + coffe.getPrice();
        }
    }
    
    public class CoffeShop {
        public static void main(String[] args) {
            Coffe myCoffee1 = new LatteCoffee();
            System.out.println(myCoffee1.getCoffeBean() + myCoffee1.getPrice());
            Coffe myCoffee2=new LatteCoffee();
            VanillaLatte xcnt=new VanillaLatte(myCoffee2);
            System.out.println(xcnt.getCoffeBean()+xcnt.getPrice());
        }
    }

    参考资料:

    https://www.cnblogs.com/shenwen/p/10768332.html

    https://blog.csdn.net/csdn15698845876/article/details/81544562

    https://segmentfault.com/a/1190000016508992

    https://my.oschina.net/liughDevelop/blog/2987320

    装饰者模式与代理模式的区别

    https://www.jianshu.com/p/c06a686dae39

    Java的23种设计模式

    https://www.cnblogs.com/pony1223/p/7608955.html

  • 相关阅读:
    tomcat端口号被占用问题
    Idea debug时报错:Command line is too long
    IDEA报错: Clone failed: Authentication failed for 'http://10.70.XXXXXXXXXXXXXXXXX'
    LiquiBase实战总结
    Iedis
    IntelliJ IDEA热部署插件JRebel免费激活图文教程(持续更新)转载
    MySql 8.0.11 客户端连接失败:2059
    windows系统 MySQL8.0.12详细安装步骤及基本使用教程
    IDEA的常见的设置和优化(功能)
    SpringBoot热启动让开发更便捷
  • 原文地址:https://www.cnblogs.com/majestyking/p/12431724.html
Copyright © 2011-2022 走看看