• 设计模式之Decorator Pattern


      在这个模式中把面向对象的好处得到了很好的体现。在类设计的时候可能会遇到组合爆炸的情况,比如《head first》中咖啡的例子。在不同的咖啡中添加不同调料的时候价格是不一样的,如果有10种调料,那么一杯咖啡的种类就由2^10=1024。但是我们不可能设计1024个类来做,就算做了维护起来也是很恐怖的。

      装饰者模式很好的利用继承来解决了这个问题,反正都是一杯咖啡,不过是在向里面加东西而已。如果只是要求咖啡的价格用面向过程的写成for+switch就可以了。在创造类型的过程中继承给人的感觉有点像这个循环的作用。下面是一个装饰者模式的例子:

    interface coffee{
    int cost();
    }
    class a implements coffee{
    coffee coffee;
    public a(coffee coffee){
    this.coffee = coffee;
    }
    public int cost() {
    if(coffee == null)
    return 1;
    else
    return coffee.cost()+1;
    }
    }

    class b implements coffee{
    coffee coffee;
    public b(coffee coffee){
    this.coffee = coffee;
    }
    public int cost() {
    if(coffee == null)
    return 2;
    else
    return coffee.cost()+2;
    }
    }

    public class Test {
    public static void main(String[] arg){
    coffee coffee = new a(null);
    System.out.println(coffee.cost());
    coffee = new b(coffee);
    System.out.println(coffee.cost());
    }
    }
  • 相关阅读:
    关于Js异常
    gitea windows 安装
    spring boot 错误页面配置
    mysql 常用用函数
    nginx 安装 tomcat pfx 格式证书
    git pull 报错
    maven 打 jar 包,包含 xml, 包含 额外 jar
    git clone 分支代码
    git 切换远程分支
    mycat 在 mysql 8.0 下 无法连接 bug
  • 原文地址:https://www.cnblogs.com/ggzwtj/p/2224975.html
Copyright © 2020-2023  润新知