我有一个基本问题让我感到困惑。
现在我有以下糟糕的设计(在我看来这是糟糕的设计)。我有一个 util 类,看起来像这样:
public class Countries
{
public boolean isCountryPresent ( String c )
{
//public static final http://en.wikipedia.org/wiki/ISO_3166-1
Set<String> myStrings = new HashSet<String>();
myStrings.add("us"); // Afghanistan
myStrings.add("af"); // Afghanistan
myStrings.add("dz"); // Algeria
myStrings.add("ao"); // Angola
myStrings.add("az"); // Azerbiajan
...
if ( myStrings.contains(c))
return true;
else
return false;
}
然后我像这样检查项目是否存在:
Countries co = new Countries ( );
boolean isPresent = co.isCountryPresent( countryISOCode );
但我在想,每次都实例化对象会浪费资源,不是吗?鉴于国家/地区数据不需要多次编译且不会更改,是否有更有效的方法来执行此操作?
最佳答案
我通常会这样做:
public class Countries
{
private static Set<String> myStrings = null
public static boolean isCountryPresent ( String c )
{
if (myStrings == null) {
myStrings = initializeSet();
}
if ( myStrings.contains(c))
return true;
else
return false;
}
private static Set<String> initializeSet()
{
//public static final http://en.wikipedia.org/wiki/ISO_3166-1
Set<String> countrySet = new HashSet<String>();
myStrings.add("us"); // Afghanistan
myStrings.add("af"); // Afghanistan
myStrings.add("dz"); // Algeria
myStrings.add("ao"); // Angola
myStrings.add("az"); // Azerbiajan
...
return countrySet;
}
}
这样它会在第一次调用该方法时初始化集合,但对于所有后续调用,旧的初始化会被缓存。
您也可以在构造函数中声明它,但我倾向于采用延迟加载方法,因此应用程序不会在启动时等待所有这些东西加载,而是加载某种需求当你真正需要它的时候。
此外,如评论中所述,这可能都应该是静态的,除非您总是重复使用相同的 Countries
整个代码中的对象,否则它将为每个新的 Countries
重做您实例化的对象。
关于java - 如何创建可由程序的不同部分重用的硬编码查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14389303/