紧耦合是指一组类彼此高度依赖。
当一个类承担太多职责时,或者当一个关注点分散在许多类而不是拥有自己的类时,就会出现这种情况。
松耦合是通过促进单一职责和关注点分离的设计来实现的。
松散耦合的类可以独立于其他(具体)类来使用和测试。
接口是用于解耦的强大工具。类可以通过接口而不是其他具体类进行通信,并且任何类都可以通过实现接口而位于该通信的另一端。
紧耦合示例:
class CustomerRepository
{
private readonly Database database;
public CustomerRepository(Database database)
{
this.database = database;
}
public void Add(string CustomerName)
{
database.AddRow("Customer", CustomerName);
}
}
class Database
{
public void AddRow(string Table, string Value)
{
}
}
松耦合示例:
class CustomerRepository
{
private readonly IDatabase database;
public CustomerRepository(IDatabase database)
{
this.database = database;
}
public void Add(string CustomerName)
{
database.AddRow("Customer", CustomerName);
}
}
interface IDatabase
{
void AddRow(string Table, string Value);
}
class Database implements IDatabase
{
public void AddRow(string Table, string Value)
{
}
}
另一个例子here https://stackoverflow.com/questions/226977/what-is-loose-coupling-please-provide-examples#227036.