image

   1: public abstract class CompressAlg
   2:    {
   3:        public abstract void Compress();
   4:        public abstract void Uncompress();
   5:        ~CompressAlg()
   6:        {
   7:            MessageBox.Show("Object release", "~FileProcessor()");
   8:        }
   9:    }

Zip

   1: public class Zip : CompressAlg
   2:   {
   3:       public override void Compress()
   4:       {
   5:           MessageBox.Show("Zip實作Compress");
   6:       }
   7:       public override void Uncompress()
   8:       {
   9:           MessageBox.Show("Zip實作Uncompress");
  10:       }
  11:   }

Rar

   1: public class Rar : CompressAlg
   2: {
   3:     public override void Compress()
   4:     {
   5:         MessageBox.Show("Rar實作Compress");
   6:     }
   7:     public override void Uncompress()
   8:     {
   9:         MessageBox.Show("Rar實作Uncompress");
  10:     }
  11: }

Factory pattern部分

輸入:  壓縮方法字串

輸出:  傳回不同壓縮方法之物件

相較於strategy pattern, 則沒有一個像factory pattern集中管理各演算法(CompressFactory),

以zip和rar為例說明 strategy pattern 強調各種相似的演算法就是一個獨立的物件

   1: public static class CompressFactory
   2: {
   3:     public static CompressAlg getInstance(string method)
   4:     {
   5:         switch (method)
   6:         {
   7:             case "zip":
   8:                 return new Zip();
   9:             case "rar":
  10:                 return new Rar();
  11:             default:
  12:                 return new Rar();
  13:         }
  14:     }
  15: }

 

 

image

Zip按鈕

   1: var cmp = CompressFactory.getInstance("zip");
   2: cmp.Compress();
   3: cmp.Uncompress();

Rar按鈕

   1: var cmp = CompressFactory.getInstance("rar");
   2: cmp.Compress();
   3: cmp.Uncompress();

Zip/Rar 動態切換按鈕

   1: string method = comboBox1.Text;
   2: var cmp = CompressFactory.getInstance(method);
   3: cmp.Compress();
   4: cmp.Uncompress();
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()