装饰者模式

原文链接

装饰器模式 允许向一个现有的对象添加新的功能,同时又不改变其结构。装饰者可以在所委托被装饰者的行为之前或之后加上自己的行为,以达到特定的目的。

4262551-3c2a5e285111d245.png

image.png

装饰器模式由组件和装饰者组成。

抽象组件(Component):需要装饰的抽象对象。
具体组件(ConcreteComponent):是我们需要装饰的对象
抽象装饰类(Decorator):内含指向抽象组件的引用及装饰者共有的方法。
具体装饰类(ConcreteDecorator):被装饰的对象。

实例:

假设我们现在去咖啡店要了一杯咖啡,可以加奶、加糖等等。咖啡和奶、糖分别有不同的价格。
咖啡就是我们的组件,奶和糖是我们的装饰者,现在我们要计算调制这样一杯咖啡花费多少。

4262551-7478370049df3bb4.png

image.png

Drink 类 (抽象组件:Component)

public interface Drink {
    double getPrice();
    String getConsist();
}

Coffee 类 (具体组件:ConcreteComponent )

public class Coffee implements Drink {
    @Override
    public double getPrice() {
        return 10;
    }

    @Override
    public String getConsist() {
        return "coffee ";
    }
}

Decorator 类(抽象装饰类:Decorator)


public abstract class Decorator implements Drink {
    protected Drink drink;

    public Decorator(Drink drink) {
        this.drink = drink;
    }

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

    @Override
    public String getConsist() {
        return drink.getConsist();
    }
}

MilkCoffee 类 (具体装饰类:ConcreteDecorator)


public class MilkCoffee extends Decorator {

    public MilkCoffee(Drink drink) {
        super(drink);
    }

    @Override
    public String getConsist() {
        String consist = super.getConsist();
        consist += " milk";
        return consist;

    }

    @Override
    public double getPrice() {
        double price = super.getPrice();
        price += 2.1;
        return price;
    }
}

SugarCoffee 类 (具体装饰类: ConcreteDecorator)

public class SugarCoffee extends Decorator{
    public SugarCoffee(Drink drink){
        super(drink);
    }

    @Override
    public double getPrice() {
        double price = super.getPrice();
        price+=0.5;
        return price;
    }

    @Override
    public String getConsist() {
        String consist = super.getConsist();
        consist+=" sugar";
        return consist;
    }
}

测试类

public class Demo {
    public static void main(String[] args) {
        Drink drink = new Coffee();
        System.out.println(drink.getConsist() + "==>" + drink.getPrice());

        drink = new MilkCoffee(drink);
        System.out.println(drink.getConsist() + "==>" + drink.getPrice());

        drink = new SugarCoffee(drink);
        System.out.println(drink.getConsist() + "==>" + drink.getPrice());

        drink = new SugarCoffee(drink);
        System.out.println(drink.getConsist() + "==>" + drink.getPrice());

    }
}

输出

coffee ==>10.0
coffee  milk==>12.1
coffee  milk sugar==>12.6
coffee  milk sugar sugar==>13.1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值