装饰者模式C#(head first设计模式)

  /// <summary>
    /// 饮料抽象类
    /// </summary>
    public abstract class Beverage
    {
        protected string description = "Unknown Beverage!";

        public string getDescription()
        {
            return description;
        }

        public abstract double cost();
    }


    /// <summary>
    /// 调料抽象类
    /// </summary>
    public abstract class CondimentDecorator : Beverage
    {
        public new abstract string getDescription();
    }


    /// <summary>
    /// 浓缩咖啡
    /// </summary>
    public class Espresso : Beverage
    {
        public Espresso()
        {
            description = "Espresso";
        }

        public override double cost()
        {
            return 1.99;
        }
    }


    public class HouseBlend : Beverage
    {
        public HouseBlend()
        {
            description = "HouseBlend";
        }

        public override double cost()
        {
            return 0.89;
        }
    }

    public class Mocha:CondimentDecorator
    {
        Beverage beverage;
        public Mocha(Beverage b)
        {
            this.beverage = b;
        }

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

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

    public class Soy : CondimentDecorator
    {
        Beverage beverage;
        public Soy(Beverage b)
        {
            this.beverage = b;
        }

        public override string getDescription()
        {
            return beverage.getDescription() + ",Soy";
        }

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

    public class Whip : CondimentDecorator
    {
        Beverage beverage;
        public Whip(Beverage b)
        {
            this.beverage = b;
        }

        public override string getDescription()
        {
            return beverage.getDescription() + ",Whip";
        }

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

    public void main(){
        //浓缩咖啡 不加调料
        Beverage beverage = new Espresso();
        Debug.WriteLine(beverage.getDescription() + ":" + beverage.cost().ToString());

        Beverage beverage2 = new HouseBlend();
        beverage2 = new Soy(beverage2);
        beverage2 = new Mocha(beverage2);
        beverage2 = new Whip(beverage2);
        Debug.WriteLine(beverage2.getDescription() + ":" + beverage2.cost().ToString());
    }

开放-关闭原则:类应该对扩展开放,对修改关闭;

装饰者模式:动态的将责任附加到对象上。想要扩展功能,装饰者提供有别于继承的另一种选择;

猜你喜欢

转载自www.cnblogs.com/huiteresa/p/10888253.html