Singleton Design Pattern

Singleton Design Pattern


Posted in : Java Posted on : April 19, 2012 at 6:52 PM Comments : [ 0 ]

In this tutorial you will learn about the Java Singleton design pattern

Singleton Design Pattern

The design patterns are common Object Oriented problem solving strategies which is language independent. There are more than 250 design patterns in OOPS.

In some particular cases you need to create only one instance of a particular class in entire application. Generally this types of instance is known as Singleton.

By using Singleton design pattern you can ensure that,

1. Only one instance of class is created.

2. Can allow multiple instances of the class easilly in future easilly.

3. Instance can be accessed globally.

An Example of Singleton design pattern is given below

SingletonDesignPatternExample.java

public class SingletonDesignPatternExample {
	private static SingletonDesignPatternExample singletonInstance;

	private SingletonDesignPatternExample() {

	}

	private static synchronized SingletonDesignPatternExample getInstance() {
		/* Checking whether the instance reference */
		if (singletonInstance == null) {
			/* Creating new Instance if no reference occurs */
			singletonInstance = new SingletonDesignPatternExample();
		}
		return singletonInstance;
	}

	public static void main(String[] args) {
		System.out.println("Objerve the Output\n");
		SingletonDesignPatternExample instance1 = new SingletonDesignPatternExample();
		System.out.println("Instance1:- " + instance1.getInstance());
		SingletonDesignPatternExample instance2 = new SingletonDesignPatternExample();
		System.out.println("Instance2:- " + instance2.getInstance());
	}
}


When you run this application it will display message as shown below:


Objerve the Output

Instance1:- SingletonDesignPatternExample@e53108
Instance2:- SingletonDesignPatternExample@e53108

Download Select Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics