简体   繁体   English

在程序执行期间,如何告诉不同的类保存到同一文件夹?

[英]How to tell different classes to save to the same folder during execution of a program?

I have a program where the typical use-case is to create a session and during this session, to perform some sequential numeric calculations, where the result of each calculation is passed as parameter to the subsequent one. 我有一个程序,其中典型的用例是创建一个会话,并在此会话期间执行一些顺序的数值计算,其中每个计算的结果均作为参数传递给后续的计算。

It is a requirement that each intermediate numeric result MUST be saved to disk, so that the following situation is achieved: 要求每个中间数值结果必须保存到磁盘,以实现以下情况:

  1. At the beginning of the session, a new, uniquely-named folder is created; 在会话开始时,将创建一个新的唯一命名的文件夹。
  2. Each calculation is sequentially run, each by a different classe, and at the end of each calculation, some file with intermediate result is saved in that folder; 每个计算都按不同的类依次运行,并且在每个计算结束时,会将具有中间结果的文件保存在该文件夹中;
  3. At the end of the session (and after the program is closed), the folder could be optionally accessed from the filesystem, and all files would be there. 在会话结束时(和程序关闭之后),可以选择从文件系统访问该文件夹,并且所有文件都位于该文件系统中。

My doubt is: 我的疑问是:

"how do I tell each class where is the folder it is supposed to save?". “如何告诉每个班级应该将其保存在哪里?”。

It is ok for us, architecturally, to have IO code in the classes, but the use of a "global" value containing the path, versus passing the path in the constructor to every class, versus another, more sensible, solution, is confusing me. 从结构上来说,我们可以在类中使用IO代码,但是使用包含路径的“全局”值,而不是将构造函数中的路径传递给每个类,以及使用另一个更明智的解决方案却令人困惑我。

Passing the path to the constructor of each class is what's known as dependency injection, and it's generally considered the preferable way of doing things, at least at a simple level. 将路径传递到每个类的构造函数的过程就是所谓的依赖注入,通常被认为是最好的处理方式,至少在简单的层次上。 The ideal solution would be to inject an instance of a file writer interface into each class as that way you can test each class using a mock writer. 理想的解决方案是将文件编写器接口的实例注入每个类,这样您就可以使用模拟编写器测试每个类。 That is more complex to implement though. 但是,实现起来比较复杂。 Either way, dependency injection is being used. 无论哪种方式,都在使用依赖项注入。

By using a global value, you couple all parts of your code to that value. 通过使用全局值,可以将代码的所有部分耦合到该值。 Such coupling should be avoided as it leads to brittle code that can easily break when changes are made. 应该避免这种耦合,因为它会导致易碎的代码,这些代码在进行更改时很容易中断。 The reason being, that in a large system it can be hard to identify all dependencies on a global item and thus understand the consequences of changing it. 原因是,在大型系统中,可能很难确定对全局项目的所有依赖关系,从而难以理解更改全局项目的后果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM