面向对象范式中的松耦合和紧耦合有什么区别? [英] What is the difference between loose coupling and tight coupling in the object oriented paradigm?

查看:27
本文介绍了面向对象范式中的松耦合和紧耦合有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能描述一下面向对象范式中松耦合和紧耦合的确切区别?

Can any one describe the exact difference between loose coupling and tight coupling in Object oriented paradigm?

推荐答案

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

Tight coupling is when a group of classes are highly dependent on one another.

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

This scenario arises when a class assumes too many responsibilities, or when one concern is spread over many classes rather than having its own class.

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

Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

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

A loosely-coupled class can be consumed and tested independently of other (concrete) classes.

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

Interfaces are a powerful tool to use for decoupling. Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface.

紧耦合示例:

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

另一个例子这里.

这篇关于面向对象范式中的松耦合和紧耦合有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆