听起来像抽象工厂模式可能对你有用。您可以创建一个EmailFactory类,它接受构造函数中的文本文件并存储它。每次在工厂中调用create()方法时,都会创建一个新的Email类,而不会加载文件,也不会将该文件作为参数传递。关于使用工厂而不是静态字段的一个好处是您的类变得更容易测试。 这里是当你使用它,它会怎样看:
EmailFactory emailFactory = new EmailFactory(file);
Email email = emailFactory.create(<whatever you need to pass in>);
Email email2 = emailFactory.create(<whatever you need to pass in>);
工厂可能是这个样子
public final class EmailFactory {
private Set<String> stopWords;
public EmailFactory(File file) {
//read stop words from file here and assign it to stopWords field
}
public Email create(<pass in what you need>) {
//filter from stopWords here
//Create new email object here
return email;
}
}
如果你不喜欢工厂做的读取文件的工作,您可以传递停用词的完成列表。
你可以阅读更多关于抽象工厂模式的方法在这里: https://en.wikipedia.org/wiki/Abstract_factory_pattern
你为什么不通过书面文件中的类的构造函数的信息? –
正如我在我的问题中提到的那样,我已经考虑过这个问题(事实上这是我目前的工作方式),但在我看来可能有更好的方法(因为这种方法涉及将完全相同的信息传递给每次创建一个新实例时,构造函数)。如果没有,那么我会坚持我正在做的,但我对Java很新,所以我认为可能有一些我错过了。 – rtb123
我明白了你的观点。你需要的是在你的'Email'类中有静态成员变量。我已经更新了我的答案,你可以在那里看到解释。 –