设计模式之装饰模式(decorator)

装饰模式

为了完成扩展,比继承更有弹性
给原有类增加扩展
注重覆盖,扩展
在设计期间考虑
是一个特别的适配器模式
适配器满足has-a()是不是的关系,装饰模式满足is-a(能不能)的关系
装饰者符合开闭原则

案例

手机套餐

手机接口

public interface Phone {

    Double getPrice();

    String getDescription();
}

被包装类

public class Apple implements Phone{
    @Override
    public Double getPrice() {
        return 9999.0;
    }

    @Override
    public String getDescription() {
        return "基础套餐";
    }
}

手机包装抽象类

public abstract class PhoneDecorator implements Phone {

    private Phone phone;

    public PhoneDecorator(Phone phone) {
        this.phone = phone;
    }

    @Override
    public Double getPrice() {
        return this.phone.getPrice();
    }

    @Override
    public String getDescription() {
        return this.phone.getDescription();
    }
}

这层可以去除,根据业务需要

包装实现类

public class BrokenScreenInsuranceDecorator extends PhoneDecorator{
    public BrokenScreenInsuranceDecorator(Phone phone) {
        super(phone);
    }

    @Override
    public Double getPrice() {
        return super.getPrice()+100;
    }

    @Override
    public String getDescription() {
        return super.getDescription()+"+1年碎屏险";
    }
}
public class ShelfLifeDecorator extends PhoneDecorator{

    public ShelfLifeDecorator(Phone phone) {
        super(phone);
    }

    @Override
    public Double getPrice() {
        return super.getPrice()+299;
    }

    @Override
    public String getDescription() {
        return super.getDescription()+"+1年保修";
    }
}

Main


public class Main {

    public static void main(String[] args) {
        Phone phone = new Apple();
        BrokenScreenInsuranceDecorator brokenScreenInsuranceDecorator
                = new BrokenScreenInsuranceDecorator(phone);
        BrokenScreenInsuranceDecorator screenInsuranceDecorator
                = new BrokenScreenInsuranceDecorator(brokenScreenInsuranceDecorator);
        ShelfLifeDecorator shelfLifeDecorator = new ShelfLifeDecorator(screenInsuranceDecorator);
        ShelfLifeDecorator decorator = new ShelfLifeDecorator(shelfLifeDecorator);

        System.out.println("套餐价格 : "+decorator.getPrice()+" 描述 : "+decorator.getDescription());
    }
}

print:套餐价格 : 10797.0 描述 : 基础套餐+1年碎屏险+1年碎屏险+1年保修+1年保修

应用

Mybatis Cache
IO类


设计模式之装饰模式(decorator)
https://www.blaaair.com/archives/she-ji-mo-shi-zhi-zhuang-shi-mo-shi-decorator
作者
Glo6f
发布于
2023年01月29日
许可协议