Decorator Pattern (3)

装饰模式(3

设计模式原则:

         对于类,我们要做到易于扩展、修改闭合。

装饰模式:

         为对象动态添加属性,提供一种可以替代继承来扩展类功能的方法。

Decorator Pattern

示例代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Security.Cryptography;

 

namespace Hello

{

   //饮料抽象类

   public abstract class Beverage

   {

      protected string description = "Unknow beverage";

      public virtual string GetDescription()

      {

        return description;

      }

      public abstract double Cost();

   }

 

   //香料装饰

   public abstract class CondimentDecorator : Beverage

   {

      public abstract override string GetDescription();

   }

 

   //Espresso

   public class Espresso : Beverage

   {

      public Espresso()

      {

        description = "Espresso";

      }

      public override double Cost()

      {

        return 1.99;

      }

   }

 

   //HouseBlend

   public class HouseBlend : Beverage

   {

      public HouseBlend()

      {

        description = "HouseBlend";

      }

      public override double Cost()

      {

        return 0.89;

      }

 

   }

 

   //Condiment Mocha

   public class Mocha : CondimentDecorator

   {

      Beverage beverage;

      public Mocha(Beverage beverage)

      {

        this.beverage = beverage;

      }

      public override string GetDescription()

      {

        return beverage.GetDescription() + ",Mocha";

      }

      public override double Cost()

      {

        return beverage.Cost() + 0.2;

      }

   }

 

   //Condiment Milk

   public class Milk : CondimentDecorator

   {

      Beverage beverage;

      public Milk(Beverage beverage)

      {

        this.beverage = beverage;

      }

      public override string GetDescription()

      {

        return beverage.GetDescription() + ",Milk";

      }

      public override double Cost()

      {

        return beverage.Cost() + 0.6;

      }

   }

   //

   class Program

   {

      static void Main(string[] args)

      {

        Beverage myBeverage = new HouseBlend();

        myBeverage = new Mocha(myBeverage);

        Console.WriteLine(myBeverage.GetDescription());

        Console.WriteLine(myBeverage.Cost());

 

        Beverage myBeverage2 = new Espresso();

        myBeverage2 = new Milk(myBeverage2);

        myBeverage2 = new Mocha(myBeverage2);

        Console.WriteLine(myBeverage2.GetDescription());

        Console.WriteLine(myBeverage2.Cost());

 

      }

   }

}

 

posted @ 2011-09-25 19:05  Erebus_NET  阅读(67)  评论(0编辑  收藏  举报