Singleton pattern
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.
We're going to create a Human class. Human class have its constructor as private and have a static instance of itself.
Human class provides a static method to get its static instance to outside world.
Step 1
Create a Class.
public class Human {
//create an object of Human
private static Human instance = new Human();
//make the constructor private so that this class cannot be
//instantiated
private Human(){}
//Get the only object available
public static Human getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello I'm alive");
}
}
Step 2
Get the only object from the singleton class.
public class MainTest {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor Human() is not visible
//Human ali = new Human();
//Get the only object available
Human ali = Human.getInstance();
//show the message
ali.showMessage();
}
}
Output
Hello I'm alive
Sign up here with your email
ConversionConversion EmoticonEmoticon