我知道松耦合和紧耦合的信息。但是我暂停了,什么时候我可以决定在哪里和什么时候使用?我不明白什么时候我需要松耦合和紧耦合?
请看: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();
}
}
上面的用法就像紧耦合!我认为紧耦合是不好的用法。但是适配器模式使用的是紧耦合。当我需要紧耦合和松耦合的时候?
发布于 2012-10-12 02:23:27
请记住,四人组模式是在依赖注入之前诞生的,它被称为松散耦合。
因此,您展示的示例Adapter模式试图展示模式是如何工作的,并不关心太多的松散耦合。
如果你希望你的代码是可测试和可替换的,那么应该使用松耦合,例如:
class CustomerService
{
private ICustomerRepository _customerRepository;
public CustomerService(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
}
要通过构造函数注入customerRepository
,您可以很容易地模拟ICustomerRepository
来进行单元测试。
发布于 2012-10-11 20:07:44
通常,您希望实现松散耦合,这意味着在可能的情况下使用抽象。
当您不能轻松地用适当的抽象替换类(Adaptee)时,适配器模式将帮助您做到这一点。
Adapter是问题适配器类的包装器。Adapter派生自抽象的Target类,并且调用代码应该只处理Target,因此它可以保持松散耦合。
发布于 2012-10-11 20:02:53
这将帮助您理解它们之间的区别,但是当您需要一个松散耦合的类时,这在很大程度上取决于应用程序的设计。What is the difference between loose coupling and tight coupling in the object oriented paradigm?
https://stackoverflow.com/questions/12838991
复制相似问题