keymasterviriya1150

Strategy pattern

Apr 19th, 2016
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.76 KB | None | 0 0
  1. /*Strategy pattern คือแพทเทิร์นที่ยอมให้มีการเปลี่ยนแปลงหรือเลือก algorithm ได้ในขณะรันไทม์ โดย client จะเป็นผู้เลือก เช่น เลือกวิธีเปรียบเทียบ object ให้เหมาะสมกับชนิดของ item ใน list เลือกวิธี validate ข้อมูลประเภทต่างๆ เป็นต้น
  2. การที่จะทำอย่างที่กล่าวมาได้ เราจำเป็นต้องแยกส่วนของ algorithm ออกไปจาก object หลัก แล้วค่อย inject เข้ามาใช้ในขณะที่ต้องการใช้ ในภาษาที่เป็น OO เรามักจะห่อ algorithm นั้นๆ ไว้ด้วย class*/
  3. public interface ICompareStrategy<E>
  4. {
  5.     int Compare(E a, E b);
  6. }
  7.  
  8. public class ListSorter<E>
  9. {
  10.     public static void Sort(List<E> list, ICompareStrategy<E> strategy)
  11.     {
  12.         for (int i = 0; i < list.Count; i++)
  13.         {
  14.  
  15.             for (int j = i + 1; j < list.Count; j++)
  16.             {
  17.  
  18.                 if (strategy.Compare(list[i], list[j]) > 0)
  19.                 {
  20.  
  21.                     var temp = list[i];
  22.  
  23.                     list[i] = list[j];
  24.  
  25.                     list[j] = temp;
  26.  
  27.                 }
  28.             }
  29.         }
  30.     }
  31. }
  32. public class Product
  33. {
  34.     public int Id { get; set; }
  35.  
  36.     public String Name { get; set; }
  37.  
  38.     public double Price { get; set; }
  39.  
  40.     public override string ToString()
  41.     {
  42.         return Name;
  43.     }
  44. }
  45. public class CompareProductByIdStrategy : ICompareStrategy<Product>
  46. {
  47.  
  48.     public int Compare(Product a, Product b)
  49.     {
  50.         return a.Id - b.Id;
  51.     }
  52.  
  53. }
  54.  
  55. public class CompareProductByPriceStrategy : ICompareStrategy<Product>
  56. {
  57.  
  58.     public int Compare(Product a, Product b)
  59.     {
  60.         return (int) Math.Round(a.Price - b.Price);
  61.     }
  62. }
  63. Product orange = new Product { Id = 35, Name = "orange", Price = 10.50 };
  64.  
  65. Product banana = new Product { Id = 12, Name = "banana", Price = 8.75 };
  66.  
  67. Product apple = new Product { Id = 64, Name = "apple", Price = 18 };
  68.  
  69. Product mango = new Product { Id = 32, Name = "mango", Price = 11.12 };
  70.  
  71. var products = new List<Product>();
  72.  
  73. products.Add(orange);
  74.  
  75. products.Add(banana);
  76.  
  77. products.Add(apple);
  78.  
  79. products.Add(mango);
  80.  
  81. PrintList(products);
  82.  
  83. /*===output===
  84.  
  85. orange
  86. banana
  87. apple
  88. mango*/
  89.  
  90. ListSorter<Product>.Sort(products, new CompareProductByPriceStrategy());
  91.  
  92. PrintList(products);
  93.  
  94. /*===output===
  95.  
  96. banana
  97. orange
  98. mango
  99. apple*/
Advertisement
Add Comment
Please, Sign In to add comment