1

Synchronize this lazy initialization is showing in sonar I want to solve this problem by static class holder idiom singleton pattern so how will make in static class holder idiom singleton pattern

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;
}

}

Deepak Singh
  • 460
  • 2
  • 7
  • 19

1 Answers1

1

Something like this:

public class Singleton {
        private Singleton() {}

        private static class SingletonHolder {
            private static final Singleton INSTANCE = new Singleton();
        }

        public static Singleton getInstance() {
            return SingletonHolder.INSTANCE;
        }
    }

With your classes:

    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;
  }
}
Sándor Juhos
  • 1,535
  • 1
  • 12
  • 19