循环依赖被认为是不良设计吗?

8 浏览
0 Comments

循环依赖被认为是不良设计吗?

在我的工作中(大部分是Java,但我相信这个问题也适用于其他语言),我经常创建两个相互“了解”的类。更具体地说,类A导入类B,类B导入类A,并且两者都有对方类型的成员变量或局部变量。\n这是否被认为是糟糕的设计?如果你愿意,是否可以称之为反模式?

0
0 Comments

是的,循环依赖是不好的设计,它违反了面向对象编程的原则。看起来你需要创建一个新的类或接口,其中包含a和b的共享参数和函数,a和b导入这个新类。

Circular dependencies occur when two or more modules depend on each other. This can lead to a variety of problems, such as difficulty in understanding and maintaining the code, increased coupling between modules, and potential runtime errors.

The main reason for circular dependencies is usually poor design or lack of proper architectural planning. It can happen when modules are tightly coupled and have interdependent relationships.

To solve circular dependencies, one possible approach is to refactor the code and break the circular dependency by introducing an intermediary module or class. This intermediary module can contain the shared parameters and functions between the two modules that have the circular dependency.

Another solution is to use dependency injection, where the dependencies are passed as parameters to the modules instead of being directly imported. This allows for looser coupling and avoids circular dependencies.

Here is an example of how to solve circular dependencies using an intermediary class:

// Module A
import { SharedClass } from './sharedClass';
class ModuleA {
  constructor() {
    this.shared = new SharedClass(this);
  }
}
export { ModuleA };
// Module B
import { SharedClass } from './sharedClass';
class ModuleB {
  constructor() {
    this.shared = new SharedClass(this);
  }
}
export { ModuleB };
// Shared Class
class SharedClass {
  constructor(module) {
    this.module = module;
  }
}
export { SharedClass };

In this example, both Module A and Module B depend on the SharedClass. Instead of directly importing each other, they import the SharedClass, which acts as an intermediary. The SharedClass then receives the module as a parameter in its constructor, allowing for the sharing of parameters and functions between the modules without creating a circular dependency.

By breaking the circular dependency and introducing an intermediary class, the code becomes more modular, easier to understand, and less prone to errors.

0
0 Comments

循环依赖是指两个或多个模块之间相互依赖,形成一个闭环的情况。循环依赖在软件设计中被认为是一种不良设计,因为它增加了代码的复杂性和维护的困难。循环依赖会导致代码难以理解和修改,增加了代码的耦合性,使得模块之间的关系变得混乱。

循环依赖的出现通常有以下原因:

1. 缺乏清晰的模块划分:模块之间的职责划分不清晰,导致相互之间产生了依赖关系。

2. 面向对象设计的不当:如果两个类之间的关系没有正确地建立,就容易出现循环依赖。

3. 引入新功能时的设计不当:当引入新功能时,没有考虑到模块之间的依赖关系,导致循环依赖的出现。

解决循环依赖的方法有以下几种:

1. 重新划分模块的职责:通过重新划分模块的职责,将相互依赖的类放在同一个模块中,从而消除循环依赖。

2. 引入中间层:引入一个中间层,将原本直接依赖的模块通过中间层来间接依赖,从而避免直接的循环依赖。

3. 接口隔离原则:通过接口隔离原则,将原本直接依赖的模块拆分成多个接口,从而减少模块之间的依赖关系,避免循环依赖的产生。

总之,循环依赖是一种不良的设计模式,会增加代码的复杂性和维护的困难。避免循环依赖的出现需要合理划分模块的职责,正确建立类之间的关系,并遵循接口隔离原则。这样可以提高代码的可读性、可维护性和可扩展性。

0