Singleton pattern java example

I found singleton design pattern a useful pattern for my applications. But, what is this design pattern?

In this pattern a single class is responsible to create an object, and you are sure that only single object is created. In this manner, this class provides a way to access its only object which can be accessed directly. No instatiate is needed.

What are the features of this type of class:

  • private costructor
  • Static instance of itself
  • Static method to get own static instance

Now, create a Singleton Class:

SingleObject.java

public class Singleton {
    private static final Singleton instance = new Singleton();
    public static Singleton getInstance() { 
       return instance; 
    }
    public void showMessage(){
       System.out.println("Hello World!");
    }
}

Now use this class into a snippet:

SingletonPatternDemo.java

public class SingletonPatternDemo {
 public static void main(String[] args) {

   //illegal construct
   //Compile Time Error: The constructor SingleObject() is not visible
   //SingleObject object = new SingleObject();

   //Get the only object available
   Singleton object = Singleton.getInstance();

   //show the message
   object.showMessage();
 }

And now verify this code!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s