设计模式(二)之装饰器模式-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

设计模式(二)之装饰器模式

简介: 定义一个代表被装饰事物的接口: public interface Coffee { public String getCoffer(); public double getPrice(); } 最初的具体事物: public class Starbucks implements Coffee { @Override pub

定义一个代表被装饰事物的接口:

public interface Coffee {

    public String getCoffer();

    public double getPrice();
}

最初的具体事物:

public class Starbucks implements Coffee {

    @Override
    public String getCoffer() {
        return "星巴克";
    }

    @Override
    public double getPrice() {

        return 10D;
    }

}

被装饰后的具体事物:

public class Seasoning implements Coffee {

    private Coffee coffee;

    public Seasoning(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public String getCoffer() {
        return coffee.getCoffer();
    }

    @Override
    public double getPrice() {
        return coffee.getPrice();
    }
}

一号装饰器:

public class SeasoningOne extends Seasoning implements Coffee {

    public SeasoningOne(Coffee coffee) {
        super(coffee);
    }

    @Override
    public String getCoffer() {
        return super.getCoffer() + " 糖";
    }

    @Override
    public double getPrice() {
        return super.getPrice() + 1.0D;
    }

}

二号装饰器:

public class SeasoningTwo extends Seasoning implements Coffee {

    public SeasoningTwo(Coffee coffee) {
        super(coffee);
    }

    @Override
    public String getCoffer() {
        return super.getCoffer() + " 牛奶";
    }

    @Override
    public double getPrice() {
        return super.getPrice() + 5.0D;
    }
}

三号装饰器:

public class SeasoningThree extends Seasoning implements Coffee {

    public SeasoningThree(Coffee coffee) {
        super(coffee);
    }
    @Override
    public String getCoffer() {
        return super.getCoffer() + " 摩卡";
    }

    @Override
    public double getPrice() {
        return super.getPrice() + 3.0D;
    }
}

使用者:

public class Consumer {

    public static void main(String[] args) {
        Coffee coffee = new SeasoningOne(new Seasoning(new Starbucks()));

        System.out.println(coffee.getCoffer() + ":" + coffee.getPrice());

        coffee = new SeasoningTwo(new SeasoningOne(new Seasoning(
                new Starbucks())));

        System.out.println(coffee.getCoffer() + ":" + coffee.getPrice());
        coffee = new SeasoningThree(new SeasoningTwo(new SeasoningOne(
                new Seasoning(new Starbucks()))));

        System.out.println(coffee.getCoffer() + ":" + coffee.getPrice());

    }
}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享: