Skip to main content

Singleton Pattern : Real Life Example and Java Code Example

Singleton Pattern

The Singleton pattern uses to prevent the instantiation of an Object or creating a new one. It is used when We need only one instance in the whole application. The singleton is similar to global variables and we can find many debates over singleton vs global variables on the internet. We can choose between singleton and global variables based on the application context, But global variables violate the encapsulation policy of OOP concepts.


Real Life Example:

The DataSource is very good example of a singleton pattern. We initialize DataSourcet object by some parameters like host,port,user and password. Every time We need the DataSource, the values of the parameters remains same So We need exactly one instance of DataSource.


Java Code Example:

There is the various implementation of the singleton, based on the initialization like eager, lazy, static block and thread safe. Below implementation called Bill Pugh Singleton Implementation is simplest and also thread safe.

package test;

/**
 * Created by chaudharys on 12/4/17.
 */
public class DataSource {
    //Private Constructor, So No one can create new object
    private DataSource(){}

    private static class  DataSourceHelper{
        private static final DataSource dataSource = new DataSource();
    }

    public static DataSource getInstance(){
        return DataSourceHelper.dataSource;
    }

}

Eager initialization

/**
 * Created by chaudharys on 12/4/17.
 */
public class DataSource {
   //Private Constructor, So No one can create new object
   private static final DataSource instance = new DataSource();
   private DataSource(){}
   public static DataSource getInstance(){
        return instance;
    }
}

Thread Safe Lazy Initialization

package test;

/**
 * Created by chaudharys on 12/4/17.
 */
public class DataSource {
    //Private Constructor, So No one can create new object
    private static DataSource instance;
    private DataSource(){}
    public static DataSource getInstance(){
       if(instance == null){
         synchronized (DataSource.class) {
            if(instance == null){
                instance = new DataSource();
            }
         }
       }
    return instance;
   }
}

Destruction of Singleton:

We can destroy the singleton by using java reflection API's. Below is the example of breaking the above singleton code.

package test;


import java.lang.reflect.Constructor;

public class Test {
    public static void main(String args[] ){
       DataSource d1 = DataSource.getInstance();
       DataSource d2;
        try {
            Constructor[] constructors = DataSource.class.getDeclaredConstructors();
            for (Constructor constructor : constructors) {
                //Below code will destroy the singleton pattern
                constructor.setAccessible(true);
                d2 = (DataSource) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Comments

Popular posts from this blog

java.lang.IllegalArgumentException: Could not instantiate implementation: org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager

If you are trying to get started with Janus Graph with Apache Cassandra. You may get the following error. Caused by: org.janusgraph.diskstorage.TemporaryBackendException: Temporary failure in storage backend at org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager.getCassandraPartitioner(CassandraThriftStoreManager.java:219) ~[janusgraph-cassandra-0.2.0.jar:na] at org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager.<init>(CassandraThriftStoreManager.java:198) ~[janusgraph-cassandra-0.2.0.jar:na] ... 48 common frames omitted Caused by: org.apache.thrift.transport.TTransportException: java.net.ConnectException: Connection refused (Connection refused) at org.apache.thrift.transport.TSocket.open(TSocket.java:187) ~[libthrift-0.9.2.jar:0.9.2] at org.apache.thrift.transport.TFramedTransport.open(TFramedTransport.java:81) ~[libthrift-0.9.2.jar:0.9.2] at org.janusgraph.diskstorage.cassandra.thrift.thriftpool.CTConnectionFactory.makeR...

com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server

If you are trying to connect Mongo DB Server and it insanely throwing following error. com.mongodb.MongoTimeoutException : Timed out after 1000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.1.10:27010, type=UNKNOWN, state=CONNECTING, exception={ com.mongodb.MongoSecurityException: Exception authenticating MongoCredential {mechanism=null, userName='user123', source='admin', password=<hidden>, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18 : 'Authentication failed.' on server 192.168.1.10:27010 . The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }}}] If you start looking the error content First you encounter with Timeout Exception which may mislead you. It is basically an authentication error. I...

Move like a Ninja on Terminal Console

If you are in IT and do a lot of stuff on terminal, this is the post for you. In the following post, we will explore various key shortcuts to jump and edit on console. Note:- Short keys may behave differnt on differnt OS systems. These keys best work with Linux sytem, For mac OS you have to enable Option key as Meta key in case of Alt . I have never checked these on windows, Please share your experinece with windows in comments. ------------------------------------------------------------------ Edit Control Move forward one char: Ctrl + f Move backward one char: Ctrl + b Move forward one word: Alt + f Move backward one word: Alt + b Move to end: Ctrl + e #Like End Move to start: Ctrl + a #Like Home Jump toggle between current location and start: Ctrl + xx Delete forward one char: Ctrl + d #Like Delete Delete backward one char: Ctrl + h #Like Backspace Delete forward one word: Alt + d Delete backward one word: Ctrl + w Delete to end: Ctrl + k Delete to start: Ctrl + u Undo: Ct...