Singleton Class & Factory Method

Java Singleton class and factory methods are the two key topics that we are going to learn today.

Java Singleton Class

If a class is able to instantiate at most for a single time then it is known as a singleton class.

public class Test {
	int x=10;
	static Test ob; //static reference
	private Test(){
		System.out.println("Private constructor");
	}
	static Test return_object() //Factory Method
	{
		if(ob==null) //Singleton class
		{
			System.out.println("Object not created");
			ob=new Test(); //object initialize
		}
		else{
			System.out.println("Object already created");
		}
		return ob;
	}

}
public class Demo {
public static void main(String[] args) {
	Test obj=Test.return_object();
	Test obj1=Test.return_object();
	System.out.println(obj.x+"\t"+obj1.x);
	System.out.println(obj+"\t"+obj1);
}
}
//OUTPUT
/*Object not created
Private constructor
Object already created
10	10
[email protected]	[email protected]*/



Did you know?

A default constructor is always same as the class. If a class is public then default constructor will be public too.

Factory Method

If the return type of method is same as the current class name then it is known as factory method in Java. Factory method should be declared as static in Java. To resolve the problem of private constructor we use factory method since private constructors cannot be invoked from outside that current class and object cannot be created.