Dependency Injection Pattern!

Ngày nay, DI là một mẫu thiết kễ phổ biến hiện nay. Nó giúp cho việc thiết kễ và thực hiện "loosely couple", sử dụng lại (reusable), có thể test (testable) trong phần mềm của bạn bằng cách giảm sự phụ thuộc của các đối tượng.

Phụ thuộc của các đối tượng. (Object Dependency)
Object có thể phụ thuộc nhau theo hai cách: tight coupling và loose coupling. Nếu các Object không có liên kết chặt chẽ với nhau thì việc thay đổi các Object sẽ đơn giản và ngược lại.

Ví dụ:
   public class C2
{
//Some code
}
public class C1
{
C2 bObject = new C2();
//Some code
}

Class C1 phụ thuộc vào C2 vì C1 chứa C2 đây gọi "tight". Nếu bạn phải tay đôi code
thì khi làm bạn chỉ có thể thoải mái thay đổi C1, còn với C2 bạn sẽ phải tính toán
không là sẽ ảnh hưởng đến C1.

Thuận lợi chính.
- Loose coupling
- Centralized configuration
- Easy testable.

Bất lợi chính.
Việc viết và thực thi DI sẽ là một cơn ác mộng nếu có quá nhiều Object và các phụ
thuộc giữa chúng.

Kiểu Dependency Injection.
- Constructor Injection.
- Setter Injection.
- Interface-based Injection.

Constructor Injection.

interface IBusinessLogic
{
//Some code
}

class ProductBL : IBusinessLogic
{
//Some code
}

class CustomerBL : IBusinessLogic
{
//Some code
}
public class BusinessFacade
{
private IBusinessLogic businessLogic;
public BusinessFacade(IBusinessLogic businessLogic)
{
this.businessLogic = businessLogic;
}
}

IBusinessLogic productBL = new ProductBL();

BusinessFacade businessFacade = new BusinessFacade(productBL);


Setter Injection.

public class BusinessFacade
{
private IBusinessLogic businessLogic;

public IBusinessLogic BusinessLogic
{
get
{
return businessLogic;
}

set
{
businessLogic = value;
}
}
}

IBusinessLogic productBL = new ProductBL();
BusinessFacade businessFacade = new BusinessFacade();
businessFacade.BusinessLogic = productBL;

Interface Injection.

interface IBusinessLogic
{
//Some code
}

class ProductBL : IBusinessLogic
{
//Some code
}

class CustomerBL : IBusinessLogic
{
//Some code
}

class BusinessFacade : IBusinessFacade
{
private IBusinessLogic businessLogic;
public void SetBLObject(IBusinessLogic businessLogic)
{
this.businessLogic = businessLogic;
}
}

IBusinessLogic businessLogic = new ProductBL();
BusinessFacade businessFacade = new BusinessFacade();
businessFacade.SetBLObject(businessLogic);

Or:

IBusinessLogic businessLogic = new CustomerBL();
BusinessFacade businessFacade = new BusinessFacade();
businessFacade.SetBLObject(businessLogic);

Bài này từ http://www.devx.com/dotnet/Article/34066/0/page/3


Comments

Popular posts from this blog

How to search and HighLight !

What's ViewState? How does use?