码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之装饰模式

时间:2015-08-21 23:23:25      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:设计模式

技术分享
Beverage.java

public abstract class Beverage {

    String description = "Unknown Berverage";

    public String getDescription(){
        return description;
    }

    public abstract double cost();
}

CondimentDecorator.java

public abstract class CondimentDecorator extends Beverage {

    public abstract String getDescription();

}

Espresso.java

public class Espresso extends Beverage {

    public Espresso() {
        description = "Espresso";
    }

    @Override
    public double cost() {
        return 1.99;
    }
}

HouseBlend.java

public class HouseBlend extends Beverage {

    public HouseBlend() {
        description = "House Blend Coffee";
    }

    @Override
    public double cost() {
        return .89;
    }
}

Mocha.java

public class Mocha extends CondimentDecorator {

    Beverage beverage;

    public Mocha(Beverage beverage) {
        this.beverage = beverage;
    }

    @Override
    public String getDescription() {
        return beverage.getDescription() + ", Mocha";
    }

    @Override
    public double cost() {
        return .20 + beverage.cost();
    }
}

Starbuzzcoffee.java

public class Starbuzzcoffee {

    public static void main(String[] args) {
        Beverage beverage = new Espresso();
        System.out.println(beverage.getDescription() + "$" + beverage.cost());

        Beverage beverage2 = new Espresso();
        beverage2 = new Mocha(beverage2);
        beverage2 = new Mocha(beverage2);
        System.out.println(beverage2.getDescription() + "$" + beverage2.cost());

        Beverage beverage3 = new HouseBlend();
        beverage3 = new Mocha(beverage3);
        System.out.println(beverage3.getDescription() + "$" + beverage3.cost());       
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

设计模式之装饰模式

标签:设计模式

原文地址:http://blog.csdn.net/zhou554291911/article/details/47843663

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!