Home Javatutorials Java Singleton Pattern



Java Singleton Pattern
Posted on: December 6, 2012 at 12:00 AM
In this section, you will learn about singleton pattern in Java.

Java Singleton Pattern

In this section, you will learn about singleton pattern in Java.

What is Singleton Pattern ?

In Java, singleton pattern is implemented to limit the instantiation of a class to one object. Similar to static field, instance of a class will occur only once per application.

How to implement ?

You can implement the singleton pattern as given below :

SingletonDemo.java

public class SingletonDemo {
// Private constructor restrict from instantiating
private static SingletonDemo instance = new SingletonDemo();

private SingletonDemo() {
}

public static SingletonDemo getInstance() {
return instance;
}

// This methods is protected due to singleton
protected static void sampleMethod() {
System.out.println("Singleton Sample Method");
}
}

For implementing "singleton pattern",  you need a private constructor( SingletonDemo() ) and a field to conatin its result(instance), and a static access method having name like getInstance().

SingletonExample.java

public class SingletonExample {
public static void main(String args[]){
SingletonDemo.sampleMethod();
}
}

 

Related Tags for Java Singleton Pattern:


More Tutorials from this section

Ask Questions?    Discuss: Java Singleton Pattern  

Post your Comment


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

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.