我什么时候需要紧密耦合和松散耦合?

lok*_*oki 1 c# design-patterns

我知道松散耦合和紧密耦合的信息.但我暂停什么时候可以决定在哪里和什么时候使用?我不明白什么时候我需要松散耦合和紧密耦合?

请看:http://www.dofactory.com/Patterns/PatternAdapter.aspx#_self1

如果你看适配器类:


  /// 
  /// The 'Adapter' class
  /// 
  class Adapter : Target
  {
    private Adaptee _adaptee = new Adaptee();

    public override void Request()
    {
      // Possibly do some other work
      //  and then call SpecificRequest
      _adaptee.SpecificRequest();
    }
  }

Run Code Online (Sandbox Code Playgroud)

以上用法就像紧紧耦合!我认为紧密耦合是糟糕的用法.但适配器模式紧密耦合使用.当我需要紧密和松散耦合?

cuo*_*gle 5

请记住,Gang of Four模式是在Dependency Injection之前诞生的,它被称为松散耦合.

因此,您展示的示例适配器模式是尝试显示模式如何工作,而不关心松耦合.

如果您希望代码可测试和可更换,则应使用松耦合,例如:

class CustomerService
{
    private ICustomerRepository _customerRepository;
    public CustomerService(ICustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }
}
Run Code Online (Sandbox Code Playgroud)

customerRepository通过构造函数注入,您可以轻松地进行模拟ICustomerRepository以进行单元测试.