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

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

问题描述

任何人都可以描述面向对象范式中松耦合和紧耦合之间的确切区别吗?

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 : IDatabase
{
    public void AddRow(string Table, string Value)
    {
    }
}

另一个示例此处.

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

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