Singleton Pattern

When we want to have only one instance of a class we can create a singleton. A few of the places where we would want to have a singleton class is in an abstract factory or a builder.

There are lots of different way’s to create singletons. A good blog post about this is the following one. Here we are going to take a look at how to implement a singleton class for a simple single threaded program.

public class Singleton {

    private static Singleton singleton;

    private Singleton(){}

    public static Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}
  • We create a class with it’s self as static attribute so there can only be one instance.
  • We make the constructor private so it can not be instantiated outside of the class.
  • We check if the attribute is not null and return it. If it’s null we create it.
public static void main(String[] args) {
        Singleton s = Singleton.getInstance();
        Singleton s1 = Singleton.getInstance();

        System.out.println(s.hashCode());
        System.out.println(s1.hashCode());
    }

We check if the hashcode is the same so we know that it is the some instance of the class. As we can see in the output this is the case and thus our singleton works.

356573597
356573597

Great now we know how to create the most simple implementation of the singleton pattern.

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