Java实用class麻烦
Java utility class trouble
我有一些数据结构需要字母表作为其构造函数的参数。因此,如果我创建它的新实例,我每次都需要提供一个字母表。
有没有更简单的方法?
我认为我可以通过使用静态实用程序 class 来简化它,就像这样
Alphabet {
public static final eng = "abc...z";
public static final ua = "абв...я";
}
但这并不能保证可扩展性。我的意思是,是的,我可以简单地向这样的 class 添加一些字母,但是用户不能添加他自己的字母,例如俄语字母。
我可以制作实用程序 class,它使用 HashMap 的私有实例,其中 K 是国家代码,V是字母表,并且支持 get/put 用户方法。所以这样我可以保证可扩展性。
但这不会让一切变得复杂吗?
编辑
假设我现在这样做
Structure instance = new Structure("abc...z");
//in another class
Structure instance = new Structure("abc...z");
实用class我可以
Structure instance = new Structure(Alphabet.eng);
//in another class
Structure instance = new Structure(Alphabet.eng);
我觉得您应该有一个界面。提供一些您自己的实现(可能是枚举),而其他开发人员仍然可以创建自己的实现。使用这个字母表的方法应该接受一个接口(不是你的枚举)。
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);
这是您要找的吗?
我有一些数据结构需要字母表作为其构造函数的参数。因此,如果我创建它的新实例,我每次都需要提供一个字母表。
有没有更简单的方法? 我认为我可以通过使用静态实用程序 class 来简化它,就像这样
Alphabet {
public static final eng = "abc...z";
public static final ua = "абв...я";
}
但这并不能保证可扩展性。我的意思是,是的,我可以简单地向这样的 class 添加一些字母,但是用户不能添加他自己的字母,例如俄语字母。
我可以制作实用程序 class,它使用 HashMap 的私有实例,其中 K 是国家代码,V是字母表,并且支持 get/put 用户方法。所以这样我可以保证可扩展性。 但这不会让一切变得复杂吗?
编辑
假设我现在这样做
Structure instance = new Structure("abc...z");
//in another class
Structure instance = new Structure("abc...z");
实用class我可以
Structure instance = new Structure(Alphabet.eng);
//in another class
Structure instance = new Structure(Alphabet.eng);
我觉得您应该有一个界面。提供一些您自己的实现(可能是枚举),而其他开发人员仍然可以创建自己的实现。使用这个字母表的方法应该接受一个接口(不是你的枚举)。
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);
这是您要找的吗?