zoukankan      html  css  js  c++  java
  • Java装饰设计模式的例子

    这里给出一个顾客购买咖啡的例子。其中咖啡可以加冰(2元),加巧克力(4元)。

    下面是面向对象中装饰模式的解决方案。

    /**
     * Created with IntelliJ IDEA.
     * User: HYY
     * Date: 13-10-27
     * Time: 下午10:49
     * To change this template use File | Settings | File Templates.
     */
    interface Product {
        public double money();
    }
    
    class Coffee implements Product{
    
        @Override
        public double money() {
            return 10;
        }
    }
    
    class Ice implements Product {
    
        private Product product;
    
        public Ice(Product product) {
            this.product = product;
        }
    
        @Override
        public double money() {
            return this.product.money() + 2;//加冰两块钱
        }
    }
    
    class Chocolate implements Product {
        private Product product;
    
        public Chocolate(Product product) {
            this.product = product;
        }
    
        @Override
        public double money() {
            return this.product.money() + 4;//加糖四块钱
        }
    }
    
    public class BuyCoffee {
        public static void main(String[] args) {
            Product coffee = new Coffee();
            Product iceCoffee = new Ice(coffee);
            Product chocolateIceCoffee = new Chocolate(iceCoffee);
            System.out.println("你买了巧克力加冰咖啡,一共:"+chocolateIceCoffee.money()+"元钱。");
        }
    }
  • 相关阅读:
    P1171 售货员的难题--搜索(剪枝)
    逆元-P3811 【模板】乘法逆元-洛谷luogu
    gcd和exgcd和lcm
    递推
    Docker hello workd
    Docker配置文件详解
    Centos7变动
    centos7安装docker
    nginx性能调优
    nginx相关
  • 原文地址:https://www.cnblogs.com/wuyou/p/3392205.html
Copyright © 2011-2022 走看看