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:
- Class is public – Object is visible to other objects in communication.
- Constructor is private – Other classes cannot instantiate directly.
- Every class has factory method that is static.
- 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