同步这个懒惰的初始化是在声纳中显示我想通过静态类持有者成语单例模式来解决这个问题所以如何在静态类持有者中制作成语单例模式
public final class ContainerFactory {
private static final int SPLIT_PANE = 1;
private static final int TABBED_PANE = 2;
private static TopLevelContainer Container = null;
public static TopLevelContainer getTopLevelContainer()
{
if(Container == null)
{
int containerType = Integer.parseInt(System.getProperty("NUEVO_CONTAINER", "1"));
switch(containerType)
{
case SPLIT_PANE:
Container = new SplitPaneContainer();
break;
case TABBED_PANE:
Container = new TabbedPaneContainer();
break;
}
}
return Container;
}
}
答案 0 :(得分:1)
这样的事情:
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
上课:
public final class ContainerFactory {
private static final int SPLIT_PANE = 1;
private static final int TABBED_PANE = 2;
private static class TopLevelContainerHolder {
private static TopLevelContainer CONTAINER = createSingleton();
}
private static TopLevelContainer createSingleton() {
int containerType = Integer.parseInt(System.getProperty("NUEVO_CONTAINER", "1"));
switch (containerType) {
case SPLIT_PANE:
return new SplitPaneContainer();
case TABBED_PANE:
return new TabbedPaneContainer();
default:
throw new IllegalStateException("Unhandled container type: " + containerType);
}
}
public static TopLevelContainer getTopLevelContainer() {
return TopLevelContainerHolder.CONTAINER;
}
}