Design Patterns – Singleton Pattern – Part II

In this post, we will discuss Singleton Pattern which is of Creational type design pattern. You can checkout the introductory post about design patterns here.

Singleton Design Pattern

Singleton design pattern is the simplest design patterns in software engineering. As Singleton is a creational type of design pattern, it is used to create an object.

In this design pattern, a single class creates an object , but also makes sure that only a single object is created. This class provides a way to access the object, so to avoid the need to instantiate the object.

Implementation

In this design pattern a class will have a private constructor and a static method to provide access to static member of the class instance. Most of the time singleton pattern is used in logger and configuration classes implementation.


package com.betterjavacode.designpatterns;

public class SingletonDemo {

private static SingletonDemo demo;

private SingletonDemo()

{

}

public static SingletonDemo getInstance()

{
if (demo == null)
demo = new SingletonDemo();

return demo;
}

public void printSingletonDemo()

{
System.out.println(" This is a singleton design pattern demo ");
}

}

Now any client code who wants to use SingletonDemo class, can do this with SingletonDemo.getInstance(). Major advantage of Singleton design pattern is it allows only one instance of object is created.

Download

Code for this post is available to download design patterns.

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