设计模式-装饰器模式

来源:互联网 发布:举而不坚,坚而不久知乎 编辑:程序博客网 时间:2024/05/22 15:10

装饰器模式(Decorator Pattern)
允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
何时使用:在不想增加很多子类的情况下扩展类。
如何解决:将具体功能职责划分,同时继承装饰者模式。

优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点:多层装饰比较复杂。
使用场景: 1、扩展一个类的功能。 2、动态增加功能,动态撤销。
注意事项:可代替继承。

举例:
星巴克根据所添加的调料收取不同的费用

/** * 饮料抽象类,所有类继承了该类 */public abstract class Beverage {    String description = "Unknow Beverage";    public String getDescription(){        return description;    }    public abstract double cost();}/** * 调料组件 */public abstract class CondimentDecorator extends Beverage {    public abstract String getDescription();}/** * 浓缩咖啡 * @author huzhiqiang * */public class Espresso extends Beverage {    public Espresso(){        this.description = "Espresso";    }    @Override    public double cost() {        // TODO Auto-generated method stub        return 1.99;    }}public class HouseBlend extends Beverage {    public HouseBlend(){        this.description = "HouseBlend";    }    @Override    public double cost() {        // TODO Auto-generated method stub        return 0.89;    }}public class Mocha extends CondimentDecorator {    Beverage beverage;    public Mocha(Beverage beverage){        this.beverage = beverage;    }    @Override    public String getDescription() {        return "Mocha " + beverage.getDescription();    }    @Override    public double cost() {        return 0.16 + beverage.cost();    }}public class Whip extends CondimentDecorator {    Beverage beverage;    public Whip(Beverage beverage){        this.beverage = beverage;    }    @Override    public String getDescription() {        return "Whip " + beverage.getDescription();    }    @Override    public double cost() {        return 0.25 + beverage.cost();    }}public class DecorateTest {    public static void main(String[] args) {        Beverage espresso = new Espresso();        System.out.println(espresso.getDescription() + ", $" + espresso.cost());        Beverage houseBlend = new HouseBlend();        houseBlend = new Mocha(houseBlend);        houseBlend = new Mocha(houseBlend);        houseBlend = new Mocha(houseBlend);        houseBlend = new Whip(houseBlend);        System.out.println(houseBlend.getDescription() + ", $" + houseBlend.cost());    }}
原创粉丝点击