大话设计模式之装饰者模式

装饰者模式:动态的给一个对象添加一些额外的职责,就增加功能来说, Decorator模式相比生成子类更为灵活。该模式以对客户端透明的方式扩展对象的功能。

参与者

 1. Component(被装饰对象的基类),定义一个对象接口,可以给这些对象动态地添加职责。
 2. ConcreteComponent(具体被装饰对象),定义一个对象,可以给这个对象添加一些职责。
 3. Decorator(装饰者抽象类),维持一个指向Component实例的引用,并定义一个与Component接口一致的接口。
 4. ConcreteDecorator(具体装饰者),具体的装饰对象,给内部持有的具体被装饰对象,增加具体的职责。

类图

类图

代码

Component(被装饰对象的基类)

// 表示价格的接口
public abstract class  Price {

    public abstract int getValue();
}

ConcreteComponent(具体被装饰对象)

// 表示价格的原价
public class PrimePrice extends Price {

    private int value;

    PrimePrice(int value){
        this.value = value;
    }

    @Override
    public int getValue(){

        return this.value;
    }

}

Decorator(装饰者抽象类)

// 定义原价的装饰器
public abstract class DecoratorPrice extends Price {

    protected Price price;

    public DecoratorPrice(Price price){
        this.price = price;
    }

    @Override
    public int getValue() {

        return price.getValue();
    }

}

ConcreteDecorator(具体装饰者)

// 采购价格2倍的价格提示Price
public class DoublePrice extends DecoratorPrice {

    public DoublePrice(Price price) {
        super(price);
    }

    @Override
    public int getValue(){

        return this.price.getValue()*2;
    }
}
// 原价基础上追加的价格
public class WholesalePrice extends DecoratorPrice {

    private int advantage;

    public WholesalePrice(Price price, int advantage) {
        super(price);

        this.advantage = advantage;
    }

    @Override
    public int getValue(){

        return this.price.getValue() + advantage;
    }
}

测试代码

public class DecoratorTest {

    public static void main(String[] args) {

        // 原价
        PrimePrice prime = new PrimePrice(120);

        // 原价基础上翻倍
        DoublePrice doublePrice = new DoublePrice(prime);

        // 翻倍基础上加价
        WholesalePrice wholesale = new WholesalePrice(doublePrice, 20);

        // 最后取得价格结果
        int result = wholesale.getValue();

        System.out.println(result);
    }

}

这里也可以先加价,然后再翻倍,其实可以有很多不同的组合


装饰者模式小结

 1. Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
 2. 通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值