Implementing the Singleton Design Pattern helps in creating only a single instance of a class. Below is a simple example for better understanding.
Class with Main Function
// Class with Main function for calling Singleton class
public class TestSingleTon {
public static void main(String[] args) {
SingleTonClass classInstance = SingleTonClass.getInstance();
System.out.println(
"My SingleTon member value is=" + classInstance.testval
);
}
}
Singleton Class
// Singleton class
public class SingleTonClass {
// Create an instance
private static SingleTonClass my_instance = new SingleTonClass();
// Private constructor
private SingleTonClass() {
// Private Constructor here
// Does not allow an object to be created outside this class
}
// Method to access the instance
public static SingleTonClass getInstance() {
return my_instance;
}
// Member variable
int testval = 10;
// If the comment is removed from the below line,
// the program will not compile.
// SingleTonClass s1 = new SingleTonClass();
}
Output
The output of this program is:
My SingleTon member value is=10
This is a simple implementation of the Singleton Design Pattern that ensures only one object is created.
There are also other ways to implement the Singleton Design Pattern, such as lazy initialization, thread-safe implementation, and handling Singleton instances across multiple JVMs.
No comments:
Post a Comment