Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Strategy pattern คือแพทเทิร์นที่ยอมให้มีการเปลี่ยนแปลงหรือเลือก algorithm ได้ในขณะรันไทม์ โดย client จะเป็นผู้เลือก เช่น เลือกวิธีเปรียบเทียบ object ให้เหมาะสมกับชนิดของ item ใน list เลือกวิธี validate ข้อมูลประเภทต่างๆ เป็นต้น
- การที่จะทำอย่างที่กล่าวมาได้ เราจำเป็นต้องแยกส่วนของ algorithm ออกไปจาก object หลัก แล้วค่อย inject เข้ามาใช้ในขณะที่ต้องการใช้ ในภาษาที่เป็น OO เรามักจะห่อ algorithm นั้นๆ ไว้ด้วย class*/
- public interface ICompareStrategy<E>
- {
- int Compare(E a, E b);
- }
- public class ListSorter<E>
- {
- public static void Sort(List<E> list, ICompareStrategy<E> strategy)
- {
- for (int i = 0; i < list.Count; i++)
- {
- for (int j = i + 1; j < list.Count; j++)
- {
- if (strategy.Compare(list[i], list[j]) > 0)
- {
- var temp = list[i];
- list[i] = list[j];
- list[j] = temp;
- }
- }
- }
- }
- }
- public class Product
- {
- public int Id { get; set; }
- public String Name { get; set; }
- public double Price { get; set; }
- public override string ToString()
- {
- return Name;
- }
- }
- public class CompareProductByIdStrategy : ICompareStrategy<Product>
- {
- public int Compare(Product a, Product b)
- {
- return a.Id - b.Id;
- }
- }
- public class CompareProductByPriceStrategy : ICompareStrategy<Product>
- {
- public int Compare(Product a, Product b)
- {
- return (int) Math.Round(a.Price - b.Price);
- }
- }
- Product orange = new Product { Id = 35, Name = "orange", Price = 10.50 };
- Product banana = new Product { Id = 12, Name = "banana", Price = 8.75 };
- Product apple = new Product { Id = 64, Name = "apple", Price = 18 };
- Product mango = new Product { Id = 32, Name = "mango", Price = 11.12 };
- var products = new List<Product>();
- products.Add(orange);
- products.Add(banana);
- products.Add(apple);
- products.Add(mango);
- PrintList(products);
- /*===output===
- orange
- banana
- apple
- mango*/
- ListSorter<Product>.Sort(products, new CompareProductByPriceStrategy());
- PrintList(products);
- /*===output===
- banana
- orange
- mango
- apple*/
Advertisement
Add Comment
Please, Sign In to add comment