2013年6月20日 星期四

[DP]深入淺出-設計模式(裝飾者模式)

裝飾者模式,當一個抽象的東西擁有許多屬性的時候,

可以透過裝飾者模式來控制 以下的例子參考了HeadFirst 的深入淺出設計模式,

以衣服為例,衣服有些是可以免運費的, 假設T-Shirt 一件加上運費100,運費為50元,

可以經由裝飾者的方式,提供FreeShopping的字樣,並且這件的衣服的價錢就降成了50(100-50)。
撰寫這段code 的時候遭遇到一個問題, 首先是clothFreeshopping的description一直都會吃到基底的cloth,
查了一下原因是,在C#裡面,override 的method 在父項必須要有virual關鍵字,不然會執行父項的method。

namespace ConsoleApplication1 {

class Program { static void Main(string[] args) {

      Cloth cloth = new T_shirt();

      Console.WriteLine(string.Format("{0} ${1}",cloth.getDescription(),cloth.cost()));

      Cloth clothFreeShopping = new T_shirt(); clothFreeShopping = new FreeShopping(clothFreeShopping);

      Console.WriteLine(string.Format("{0} ${1}", clothFreeShopping.getDescription(), clothFreeShopping.cost()));

      Console.Read(); } }

//定義抽象類別

public abstract class Cloth {

     protected string description = "Unknown Cloth";

     public virtual string getDescription() { return description; }

     public abstract double cost();

}

     public abstract class CondimentDecorator : Cloth { //public abstract string getDescription(); }

     class T_shirt : Cloth{

           public T_shirt() { description = "T-Shirt"; }

           public override double cost() { return 100; }

      }

      class shirt : Cloth {

            public shirt() {

                 description = "T-Shirt";

             }

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

             public class FreeShopping:CondimentDecorator {

                    Cloth cloth;

              public FreeShopping(Cloth cloth) {

                    this.cloth = cloth; }

              public override string getDescription() { return cloth.getDescription() + ", FreeShopping"; }

              public override double cost() { return -50 + cloth.cost(); }

   }

}

沒有留言 :

張貼留言