美文网首页
装饰(decorate)模式

装饰(decorate)模式

作者: 莫库施勒 | 来源:发表于2019-08-02 19:01 被阅读0次
    public interface Beverage {
        public double cost();
    }
    public class HouseBlend implements Beverage{
        @Override
        public double cost() {
            return 1;
        }
    }
    public class DarkRoast implements Beverage{
        @Override
        public double cost() {
            return 1;
        }
    }
    public abstract class CondimentDecorator implements Beverage{
        protected Beverage beverage;
    }
    public class Mocha extends CondimentDecorator {
    
        public Mocha(Beverage beverage) {
            this.beverage = beverage;
        }
    
        @Override
        public double cost() {
            return 1 + beverage.cost();
        }
    }
    public class Milk extends CondimentDecorator {
    
        public Milk(Beverage beverage) {
            this.beverage = beverage;
        }
    
        @Override
        public double cost() {
            return 1 + beverage.cost();
        }
    }
    public class StartbuzzCoffee {
        public static void main(String[] args) {
            Beverage beverage = new HouseBlend();
            beverage = new Mocha(beverage);
            beverage = new Milk(beverage);
            System.out.println(beverage.cost());
        }
    }
    

    相关文章

      网友评论

          本文标题:装饰(decorate)模式

          本文链接:https://www.haomeiwen.com/subject/prsrdctx.html