如何使用顶级应用程序的实例化信息创建低级对象?
我有一个应用程序可以读取其中包含各种用户设置的输入文件。其中一些设置适用于在非常低级别实例化的非常具体的类。但输入文件会被读取,并且设置会存储在应用程序的顶层。
使用在顶层读取的信息来实例化低级类(从顶层删除了几个链接)的设计模式是什么?
I have an application that reads an input file with various user settings in it. Some of these settings apply to very specific classes that are instantiated at a very low level. But the input file is read and the settings are stored at the top level of the app.
What's the design pattern here for instantiating a low-level class (that's several links removed from the top level) using information that's read at the top level?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让顶层仅处理抽象,并使用平台的反射库来实例化具体类型。
工厂类/提供程序可能很有用,您可以向其传递一组可用于构造具体类型的属性。
将它们放在一起,在 Java 中可能看起来像这样:
然后将反射性地构造
MyObjFactory
,并可用于构造MyObj
。Have the top level deal with abstractions only, and use your platform's reflection library to instantiate the concrete types.
A factory class/provider can be useful, where you can pass it a set of properties that it can use to construct the concrete type.
Putting it all together, it might look like this in Java:
Then
MyObjFactory
would be constructed reflectively, and could be used to construct aMyObj
.通常有一个包含全局属性的全局 App 对象,因此,低级类可以从该单点访问它们需要的所有内容。如果项目不是很复杂,这个解决方案是相当易于管理的。
作为一种变体,您可以让全局应用程序对象实现低级类感兴趣的接口,并在构造时注入它。与 (C#) 类似:
仅向对象传递其所需的最少信息。因此,您可以保持具体的“主力”类(文件)简单且松散耦合,并在需要时稍后处理参数传递。
It's customary to have single global App object which contains global properties, so, low-level classes can access everything they need from that single point. If project is not very complex this solution is quite manageable.
As a variation you can have global application object implementing interfaces in which low-level classes interested and inject it at the construction time. Like (C#):
Pass to object only minimum information it needs. So you can keep your concrete "workhorse" classes (files) simple and loosely coupled and deal with parameter passing later, if needed.