C#裝飾器模式(Decorator Pattern)實例教程
本文以實例形式詳細講述了C#裝飾器模式的實現(xiàn)方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
現(xiàn)假設有一個公司要做產品套餐,即把不同的產品組合在一起,不同的組合對應不同的價格。最終呈現(xiàn)出來的效果是:把產品組合的所有元素呈現(xiàn)出來,并顯示該組合的價格。
每個產品都有名稱和價格,首先設計一個關于產品的抽象基類。
public abstract class ProductBase { public abstract string GetName(); public abstract double GetPrice(); }
所有的產品都必須繼承這個基類,比如家居用品、電器產品等,把這些具體的產品提煉成一個繼承ProductBase的子類。
public class ConcretProuct : ProductBase { private string _name; private double _price; public ConcretProuct(string name, double price) { this._name = name; this._price = price; } public override string GetName() { return _name; } public override double GetPrice() { return _price; } }
然后考慮產品組合。比如賣平底鍋,可能送醬油,也有可能送醬油+老壇酸菜,可能的組合包括:
1. 平底鍋
2. 平底鍋 + 醬油
3. 平底鍋 + 醬油 + 老壇酸菜
在這里,可以把醬油,老壇酸菜看作是裝飾器,因為每加一個產品,都是在原有的基礎上增加的。比如做"平底鍋 + 醬油"這個組合,是在"平底鍋"的基礎上增加了"醬油"。
現(xiàn)在把醬油、老壇酸菜也設計成繼承ProductBase的子類,也就是裝飾器類。不過,與ConcretProuct類不同的是,裝飾器類需要引用ProductBase,在這里,無論是顯示產品組合還是計算產品產品組合價格,都離不開這個引用的ProductBase。
public class Decorator : ProductBase { private ProductBase _product = null; private string _name; private double _price; public Decorator(ProductBase product, string name, double price) { this._product = product; this._name = name; this._price = price; } public override string GetName() { return string.Format("{0},{1}", _product.GetName(), _name); } public override double GetPrice() { return _product.GetPrice() + _price; } }
以上,顯示產品名稱的時候,把裝飾器類Decorator引用的ProductBase的名稱和當前名稱組合起來,以逗號分隔;顯示產品價格的時候,把引用的ProductBase的價格和當前價格相加。
客戶端如下:
class Program { static void Main(string[] args) { ConcretProuct livingProduct = new ConcretProuct("平底鍋",100); Console.WriteLine(PrintProductDetails(livingProduct)); Decorator dec1 = new Decorator(livingProduct,"海鮮醬油",10); Console.WriteLine(PrintProductDetails(dec1)); Decorator dec2 = new Decorator(dec1, "老壇酸菜",12); Console.WriteLine(PrintProductDetails(dec2)); Console.ReadKey(); } private static string PrintProductDetails(ProductBase product) { return string.Format("產品組合:{0} 價格:{1}", product.GetName(), product.GetPrice()); } }
運行結果如下圖所示:
希望本文所述對大家C#程序設計的學習有所幫助。
相關文章
C#實現(xiàn)winform自動關閉MessageBox對話框的方法
這篇文章主要介紹了C#實現(xiàn)winform自動關閉MessageBox對話框的方法,實例分析了C#中MessageBox對話框的相關操作技巧,需要的朋友可以參考下2015-04-04解析C#多線程編程中異步多線程的實現(xiàn)及線程池的使用
這篇文章主要介紹了C#多線程編程中異步多線程的實現(xiàn)及線程池的使用,同時對多線程的一般概念及C#中的線程同步并發(fā)編程作了講解,需要的朋友可以參考下2016-03-03