我有一些数据结构,要求字母表作为其构造函数的参数。因此,如果我创建它的新实例,我将需要每次提供一个字母表。
有更简单的方法吗?我认为我可以通过使用静态实用程序类来将其辛化,如下所示
Alphabet {
public static final eng = "abc...z";
public static final ua = "абв...я";
}但这不能保证可扩展性。我的意思是,是的,我可以简单地添加一些字母到这样的类,但用户不能添加他自己的字母表,例如俄语字母。
我可以创建实用程序类,它使用HashMap的私有实例,其中K是国家代码,V是字母表,并为用户支持get/put方法。这样我才能保证可扩展性。但这难道不让一切变得复杂吗?
编辑
假设我现在这么做了
Structure instance = new Structure("abc...z");
//in another class
Structure instance = new Structure("abc...z");根据实用程序类,我可以这样做。
Structure instance = new Structure(Alphabet.eng);
//in another class
Structure instance = new Structure(Alphabet.eng);发布于 2016-02-10 14:53:42
我觉得你应该有个界面。提供一些您自己的实现(可能是枚举),而另一个开发人员仍然可以创建自己的实现。使用此字母表的方法应该接受一个接口(而不是您的枚举)。
interface Alphabet {
String characters();
}
enum KnownAlphabet implements Alphabet {
ENG("abc...z"),
UA("абв...я");
private final String characters;
KnownAlphabet(String characters) {
this.characters = characters;
}
@Override
public String characters() {
return characters;
}
}
class Structure {
public Structure(Alphabet alphabet) {
String characters = alphabet.characters();
// do whatever you were doing with the characters before
}
}那你的:
Structure instance = new Structure(Alphabet.eng);改为:
Structure instance = new Structure(KnownAlphabet.ENG);这就是你要找的吗?
https://stackoverflow.com/questions/35317897
复制相似问题