標籤:mil mvc ges depend ace public category color ret
本文參考:http://www.cnblogs.com/willick/p/3223042.html
1、在一個類內部,不通過建立對象的執行個體而能夠獲得某個實現了公開介面的對象的引用。這種"需要",就稱為依賴注入(Dependency Injection)。
2、依賴注入和和所謂的控制反轉(Inversion of Control )是一個意思。
3、依賴注入是通過介面實現松耦合的設計模式,是解耦的重要手段。
4、依賴注入分為兩步:移除對組件的依賴;通過類的構造器(或setter訪問器)來傳遞實現了公開介面的組件的引用。
5、樣本:
public class Product { public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } }
public interface IValueCalculator { decimal ValueProducts(params Product[] products);}
public class LinqValueCalculator : IValueCalculator { public decimal ValueProducts(params Product[] products) { return products.Sum(p => p.Price); } }
public class ShoppingCart { //計算購物車內商品總價錢 public decimal CalculateStockValue() { Product[] products = { new Product {Name = "西瓜", Category = "水果", Price = 2.3M}, new Product {Name = "蘋果", Category = "水果", Price = 4.9M}, new Product {Name = "空心菜", Category = "蔬菜", Price = 2.2M}, new Product {Name = "地瓜", Category = "蔬菜", Price = 1.9M} }; IValueCalculator calculator = new LinqValueCalculator(); //計算商品總價錢 decimal totalValue = calculator.ValueProducts(products); return totalValue; } }
public class ShoppingCart { IValueCalculator calculator; //建構函式,參數為實現了IValueCalculator介面的類的執行個體 public ShoppingCart(IValueCalculator calcParam) { calculator = calcParam; } //計算購物車內商品總價錢 public decimal CalculateStockValue() { Product[] products =
{ new Product {Name = "西瓜", Category = "水果", Price = 2.3M}, new Product {Name = "蘋果", Category = "水果", Price = 4.9M}, new Product {Name = "空心菜", Category = "蔬菜", Price = 2.2M}, new Product {Name = "地瓜", Category = "蔬菜", Price = 1.9M} }; //計算商品總價錢 decimal totalValue = calculator.ValueProducts(products); return totalValue; } }
這樣就徹底斷開了ShoppingCart和LinqValueCalculator之間的依賴關係,使用實現了IValueCalculator介面的類(樣本中的LinqValueCalculator)的執行個體引用作為參數,傳遞給ShoppingCart類的建構函式。ShoppingCart類不知道也不關心這個實現了IValueCalculator介面的類是什麼,更沒有責任去操作這個類。
ShoppingCart、LinqValueCalculator和IValueCalculator之間的關係:
【ASP.NET MVC 學習筆記】- 04 依賴注入(DI)