美文网首页
装饰者模式

装饰者模式

作者: 恶魔幻心 | 来源:发表于2018-12-17 23:28 被阅读0次

    动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案

    饮料抽象类

    public abstract class Beverage{

        String description = "";

        public String getDescription(){  return description;}

       public abstract double cost();

    }

    调料抽象类---装饰者类

    public abstract class CondimentDecorator extend Beverage{

        public  abstract String getDescription();

    }

    浓缩咖啡

    public class Espresso extends Beverage(){

        public Espresso(){  description = "Espresso Coffee";    }

        public double cost(){  return 1.99;}

    }

    摩卡咖啡--具体装饰者

    public class Mocha extends CondimentDecorator(){  

        Beverage beverage;

        public Mocha(Beverage beverage){this.beverage = beverage;}

          public Mocha getDescription(){   return beverage.getDescription() + ",Mocha" ;}  

          public double cost(){    return 0.2 + beverage.cost();}

    }

    Main

    Beverage beverage = new Espresso();

    beverage = new Mocha(beverage);//Mocha 装饰

    beverage = new Mocha(beverage);//Mocha 装饰

    beverage = new Whip(beverage);//Whip 装饰

    System.out.print(beverage.getDescription()+" $ " + bevarage.cost())


    result:

    Espresso Coffee,Mocha,Mocha,Whip $ 3.44

    扩展:FilterInputStream  装饰者对象

    相关文章

      网友评论

          本文标题:装饰者模式

          本文链接:https://www.haomeiwen.com/subject/famhkqtx.html