Factory Class in Java

Previous
Next

Factory Class:

  • These are called design pattern classes.
  • These objects have special behavior from plain objects.
  • We need to implement following rules to get that behavior

Rules:

  1. Class is public – Object is visible to other objects in communication.
  2. Constructor is private – Other classes cannot instantiate directly.
  3. Every class has factory method that is static.
  4. Factory method returns instance on request.
public class FactoryClass
{
	private FactoryClass()
	{
		System.out.println("Factory class instantiated");
	}
	public static FactoryClass getObject()
	{
		return new FactoryClass();
	}
	public void fun()
	{
		System.out.println("Factory class functionality...");
	}
}

class Access 
{
	public static void main(String[] args) 
	{
		// FactoryClass obj = new FactoryClass();  -> Error : Private access
		FactoryClass obj = FactoryClass.getObject();
		obj.fun();
	}
}

Note: The main difference between Factory and Singleton is “Factory class” can be instantiated many times where as “Singleton” can instantiate only once.

public class Factory
{
	private Factory()
	{
		// logic...
	}
	public static Factory getObject()
	{
		Factory obj = new Factory();
		return obj ;
	}
}

class Access 
{
	public static void main(String[] args) 
	{
		// Factory f = new Factory(); -> Error :
		Factory f1 = Factory.getObject();
		Factory f2 = Factory.getObject();

		System.out.println("f1 addr : " + f1);
		System.out.println("f2 addr : " + f2);
	}
}

Output:
f1 addr : Factory@106d69c
f2 addr : Factory@52e922
Previous
Next

Add Comment

Courses Enquiry Form