Search code examples
javathread-safetysingletonfactory-pattern

How to use a factory pattern to get the instance of my Database Client?


Below is my Interface -

public interface IDBClient {

    public String read(String input);

    public String write(String input);

}

This is my Implementation of the Interface -

public class DatabaseClient implements IDBClient {

    @Override
    public String read(String input) {

    }

    @Override
    public String write(String input) {

    }
}

Now I am thinking to write Thread Safe Singleton Factory to get the instance of DatabaseClient so that I can call read and write method accordingly.. So I wrote like this by following the Initialization On Demand Holder idiom, it is still incomplete -

public class DatabaseClientFactory {

    public static DatabaseClientFactory getInstance() {
        return ClientHolder.s_instance;
    }

    private static class ClientHolder {

    }
}

And I am not sure how to get the instance of DatabaseClient correctly in my above Factory? Do I need to add another method getClient() to get the instance of DatabaseClient and then call like this -

IDBClient client = DatabaseClientFactory.getInstance().getClient();
client.read(input); // or client.write(input)

Solution

  • You shold use Initialization-on-demand holder idiom, implementing your factory:

    public class DatabaseClientFactory {
        private DatabaseClientFactory() {}
    
        private static class LazyHolder {
            private static final DatabaseClient INSTANCE = new DatabaseClient();
        }
    
        public static DatabaseClient getInstance() {
            return LazyHolder.INSTANCE;
        }
    }
    

    This code doesn't need synchronization because of the contract of the class loader:

    • the class loader loads classes when they are first accessed
    • all static initialization is executed before anyone can use class
    • class loader has its own synchronization that make previous two points guaranteed to be thread safe