坚实的原则。如何不让所有东西都卡在更高级别 class?

SOLID principles. How to not get everything jammed at the higher level class?

我刚刚完成了一个主要使用 Utility classes 的 java 应用程序,然后我在周末阅读了 SOLID 原则,因此我正在重构整个应用程序以遵循该原则。我在尝试时遇到了一个问题,因此,我一定是做错了,所以任何人都可以引导我走上正确的道路吗? 示例:

public interface ID { }

public class D implements ID {
  //this class has a lot of dependencies that I do not want in class B but at some point
 // I have to create it. When is that point?
}

public interface IC { }

public class C implements IC {
  //this class has a lot of dependencies that I do not want in class B
}

public interface IB { }

public class B implements IB {
  public IC c;
  public ID d; 

  // this class depends on the 2 (or more) interfaces IC and ID so 
  // it won't have dependencies on concrete classes. But if the 
  // concrete classes are not used, then they all start bubbling up to the          
  // higher level class (let say class A below), and class A would know about and have 
  // dependencies on way so many objects, doesn't it?
}

public class A {
   ID d = new D();
   IC c = new C();
   IB b = new B(d, c); // b could given to some other classes
}

如您所见,抽象层次越多,对象越多,情况就越糟。你有什么减少这种情况的技术?

我的第一个想法是在中间有一个接口的客户端,它知道关于这些接口的具体 classes 的所有信息(有点像工厂 class),然后 class A 将使用该客户端 class,但问题仍然存在。 Class A 依赖于客户端 class,客户端 class 依赖于其他具体的 classes。我只是制作了一条较长的链条,而不是许多短链条。

我觉得这个设计不错。没有必要在 class A 之上创建更多的抽象层,因为那样 - 正如你正确意识到的那样 - 它永远不会结束。系统必须有优势,抽象应该在某些地方解决。在 class A 中做是可以的,只要这个 class 只负责将其他对象连接在一起(所以你可以调用 class A "Configuration")。

因此,只要您只想使用没有任何框架的普通 java,您就可以采用这种设计。使用 Spring(或任何其他依赖注入库)进行 DI 可能是一个加号,但只有在您觉得需要时才引入它。顺便说一下,使用 spring 的 JavaConfig 进行依赖注入会产生与当前 class A 几乎相同的代码,并带有一些注释。