c++装载机类
我正在考虑一个加载器类并想出了两种不同的方法。
class Loader{
public:
Loader(const Path& path);
File load() const;
private:
Path path_;
};
vs
class Loader{
public:
Loader();
File load(const Path& path) const;
};
使用第一种方法,每个文件需要一个 Loader,并且 Loader 类代表一种状态。使用第二个,我可以使用一个加载器类加载不同的文件。 除了这些明显的差异之外,您会选择哪种方法?为什么或者是否有第三种可能更好的方法?
I was thinking of a loader class and came up with two different approaches.
class Loader{
public:
Loader(const Path& path);
File load() const;
private:
Path path_;
};
vs
class Loader{
public:
Loader();
File load(const Path& path) const;
};
With the first approach, I need one Loader per file and the Loader class represents a state. With the second one, I can load different Files with one loader class.
Besides these obvious differences which approach would you choose and why or is there a third maybe superiour way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
还有其他方法。
如果加载文件时在
Loader
类中不维护任何状态,那么您可以简单地编写一个自由函数,或者如果需要,也可以将该函数设为
static
有时这样的解决方案完全取决于情况,有时取决于公司/程序员的个人喜好和品味。没有一种最佳解决方案!
您甚至可以选择在
File
类本身中编写load
函数:在这种情况下,也许您想要更改函数的名称:
open( )
似乎比load()
更好。There are other approaches as well.
If you don't maintain any state in the
Loader
class when loading a file, then you can simply write a free functionOr you can make the function
static
if you want it to be a member functionSometimes such solutions entirely depend on the situation, and sometimes on company/programmer's personal preferences and taste. There is no one best solution as such!
You can even choose to write the
load
function in theFile
class itself:In this, maybe, you would want to change the name of the function:
open()
seems better thanload()
.这取决于您何时知道
路径
信息。例如,如果您在类中有一个 Loader 成员,但在调用该类的构造函数时尚不知道路径,则需要执行类似于第二种方法的操作。如果您已经知道路径,那么第一种方法可能会更好。一般来说,这不是一个一刀切的问题。
It depends on when the
path
information becomes known to you. If e.g. you have aLoader
member in a class, but do not already know the path when you call that class' constructor you would need to do something like the second approach. If you do know the path already then the first approach might be better.In general, this is not an one size fits all question.
这取决于您在应用程序中的需要。以后还需要状态吗?或者将初始化的加载程序传递到其他地方来执行实际加载?那么你可能需要国家。否则不会。
不存在通用的“最佳”解决方案。
It is just up to what you need in your application. Do you need the state later? Or pass the initialized loader somewhere else to do the actual load? Then you might need the state. Otherwise not.
There is no general "best" solution.