2

I am trying to write a Singleton Lazy Loading Pattern. Here is the class:

public class IMDBLookup {

    private static class LazyLoad {
        private static final IMDBLookup IMDB_LOOKUP;

        static {
            IMDB_LOOKUP = new IMDBLookup();
        }
    }

    public static IMDBLookup getInstance() {
        return IMDBLookup.LazyLoad.IMDB_LOOKUP;
    }
}

I am wondering whether or not I am doing it in a right way?

Thanks in advance.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331

4 Answers4

2

I prefer to use enum for simplicity.

public enum IMDBLookup {
    INSTANCE;
    // add fields and methods here.
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1
public class IMDBLookup {

    private IMDBLookup(){
        // without this I do not get why is it a singleton
        // anyone could create instances of your class by the thousands
    }

    private static class LazyLoad {
        private static final IMDBLookup IMDB_LOOKUP;

        static {
            IMDB_LOOKUP = new IMDBLookup();
        }
    }

    public static IMDBLookup getInstance() {
        return IMDBLookup.LazyLoad.IMDB_LOOKUP;
    }
}

and you should probably use an enum (not completely sure I do this right)

public class IMDBLookup {

    private IMDBLookup(){
    }

    private static enum LazyLoad {
        IMDB_LOOKUP_INSTANCE;
        private static final IMDB_LOOKUP = new IMDBLookup();
    }

    public static IMDBLookup getInstance() {
        return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
    }
}
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
1

That is correct. You may want to simplify the inner (holder) class as private static final IMDBLookup IMDB_LOOKUP = new IMDBLookup(); for brevity (to get rid of the static initializer block.)

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
0

The advice you to think about clone & serialize

import java.io.Serializable;

public class DBConnectionInner implements Cloneable, Serializable {

    private static final long serialVersionUID = 1173438078175185035L;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new CloneNotSupportedException("CLONE NOT SUPPORT FOR SINGTELTON");
    }

    protected Object readResolve() {
        return getInstance();
    }

    private DBConnectionInner() {}

    static DBConnectionInner getInstance() {
        System.out.println("DBConnectionInner getInstance");
        return LazyInit.instance;
    }

    public static class LazyInit {
        private static final DBConnectionInner instance = new DBConnectionInner();
    }

}
Priyanka
  • 341
  • 3
  • 13