在面向对象范式中,有人能准确地描述松耦合和紧耦合之间的区别吗?


当前回答

当两个对象松散耦合时,它们可以相互作用,但知之甚少 对方。

松散耦合设计允许我们构建能够处理变更的灵活的OO系统。

观察者设计模式是一个让类松散耦合的好例子,你可以在维基百科上看到它。

其他回答

紧密耦合是指一组类彼此高度依赖。

当一个类承担了太多的责任,或者当一个关注点分散到许多类而不是拥有自己的类时,就会出现这种情况。

松耦合是通过促进单一责任和关注点分离的设计实现的。

松耦合类可以独立于其他(具体的)类使用和测试。

接口是用于解耦的强大工具。类可以通过接口而不是其他具体类进行通信,并且任何类都可以通过实现接口而处于通信的另一端。

紧密耦合的例子:

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)
    {
    }
}

另一个例子。

我的理解是,与松散耦合的体系结构相比,紧密耦合的体系结构并没有为更改提供很多灵活性。

但是对于松散耦合的体系结构,消息格式或操作平台或修改业务逻辑不会影响另一端。如果系统因改造而关闭,当然另一端在一段时间内不能访问服务,但除此之外,未更改的一端可以恢复消息交换,就像改造之前一样。

在面向对象设计中,耦合量指的是一个类的设计依赖于另一个类的设计的程度。换句话说,A类力的变化与B类力的变化相关的频率是多少?紧耦合意味着两个类经常一起更改,松耦合意味着它们大部分是独立的。一般来说,推荐使用松耦合,因为它更容易测试和维护。

你可能会发现Martin Fowler的这篇论文(PDF)很有帮助。

如果一个对象的创建/存在依赖于另一个不能被剪裁的对象,它的紧密耦合。如果依赖关系可以被裁剪,那么它的松散耦合。考虑Java中的一个例子:

class Car {

    private Engine engine = new Engine( "X_COMPANY" ); // this car is being created with "X_COMPANY" engine
    // Other parts

    public Car() { 
        // implemenation 
    }

}

Car类的客户端只能创建一个“X_COMPANY”引擎。

考虑打破这种耦合的能力来改变它:

class Car {

    private Engine engine;
    // Other members

    public Car( Engine engine ) { // this car can be created with any Engine type
        this.engine = engine;
    }

}

现在,Car不依赖于“X_COMPANY”的引擎,因为它可以用类型创建。

Java特有的注意事项:仅仅为了解耦合而使用Java接口并不是一种合适的设计方法。在Java中,接口有一个目的——充当契约,从本质上提供解耦合行为/优势。

Bill Rosmus在公认答案中的评论有一个很好的解释。

一般来说,紧密耦合是不好的,但大多数时候,因为它降低了代码的灵活性和可重用性,它使更改更加困难,它阻碍了可测试性等。

Tightly Coupled Object is an object need to know quite a bit about each other and are usually highly dependent on each other interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects, In small application we can easily identify the changes and there is less chance to miss anything. But in large applications these inter-dependencies are not always known by every programmer or chance is there to miss changes. But each set of loosely coupled objects are not dependent on others.

简而言之,我们可以说,松耦合是一种设计目标,它寻求减少系统组件之间的相互依赖关系,目的是降低一个组件的更改将要求任何其他组件进行更改的风险。松散耦合是一个更通用的概念,旨在增加系统的灵活性,使其更可维护,并使整个框架更“稳定”。

耦合指的是一个元素对另一个元素的直接认识程度。我们可以说A和B,只有B在A改变其行为时才改变其行为。松散耦合的系统可以很容易地分解为可定义的元素。