gpt4 book ai didi

java - 坚实的原则。如何在更高级别的类(class)中不被卡住?

转载 作者:行者123 更新时间:2023-12-02 03:55:51 25 4
gpt4 key购买 nike

我刚刚完成了一个主要使用实用程序类的 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
}

正如你所看到的,抽象级别越多,对象越多,情况就越糟糕。你有什么技术来减少这种情况?

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

最佳答案

这个设计我觉得不错。没有必要在 A 类之上创建更多的抽象层,因为那样的话——正如你正确认识到的那样——它永远不会结束。系统必须有一个边缘,抽象应该在某个地方得到解决。在类 A 中执行此操作没问题,只要此类仅负责将其他对象连接在一起(因此您可以将类 A 称为“配置”)。

因此,只要您只想使用纯 java 而不使用任何框架,那么您就可以采用这种设计。使用 Spring(或任何其他依赖注入(inject)库)进行 DI 可能是一个优点,但仅在您认为需要时才引入它。顺便说一句,使用 spring 的 JavaConfig 进行依赖注入(inject)将产生与当前的 A 类几乎相同的代码,并带有一些注释。

关于java - 坚实的原则。如何在更高级别的类(class)中不被卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35460332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com