摘要:(200-07-16) C#.NET 裝飾模式(Decorate Pattern)
1----* Aggregation(聚合)
介面
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace cspattern { public interface IProductCal { //存取產品名稱 String productName{set;get;} //取單價 Decimal price { set; get; } //計算價格 Decimal calPrice(); } }
實作介面的類別1 :義大利麵
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace cspattern { public class 義大利麵:IProductCal { //Data Field private String _productName; private Decimal _price; #region IProductCal 成員 public string productName { get { return this._productName; } set { this._productName = value; } } public decimal price { get { return this._price; } set { this._price = value; } } public decimal calPrice() { return this._price * 2; } #endregion } }
實作介面的類別2:沙拉
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace cspattern { public class 沙拉:IProductCal { //Data Field private String _productName; private Decimal _price; #region IProductCal 成員 public string productName { get { return this._productName; } set { this._productName = value; } } public decimal price { get { return this._price; } set { this._price = value; } } public decimal calPrice() { return this._price * 3; } #endregion } }
實作介面的類別3:收銀機
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace cspattern { class 收銀機:IProductCal { //Data Field private String _productName; private Decimal _price; //聚合Aggregation //集合 private System.Collections.Generic.List<IProductCal> 餐點 = new List<IProductCal>(); #region IProductCal 成員 public string productName { get { return this._productName; } set { this._productName = value; } } public decimal price { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public decimal calPrice() { Decimal totalamt = 0M; //計價 foreach (IProductCal p in this.餐點) { totalamt += p.calPrice(); } return totalamt; } #endregion //Method 加入你點的餐點 public void addProduct(IProductCal product) { if (product != null) { //收起來 this.餐點.Add(product); } } } }
主程式
//點一樣 //收銀機 收銀機 cal = new 收銀機(); 沙拉 s = new 沙拉() { price = 100, productName = "沙拉" }; //單點價格 MessageBox.Show(s.calPrice().ToString()); cal.addProduct(s); cal.addProduct(new 義大利麵() { price = 100, productName = "沙拉" }); //計算 MessageBox.Show(cal.calPrice().ToString());