Factory Method Pattern


This is the most fundamental creational pattern. All others are extensions of this pattern.

Most object oriented programming languages provide a new operator (or its equivalent) that is used to instantiate an object of the given class. This is the simplest way of creating instances (the Java reflection API can be used to create instances - but that is certainly not simple)

But there are occasions when it is important to control the instantiation. We might want to ensure instantiation in groups, or we want to limit the number of objects, we want to simplify the API . . There are many different scenarios when we need to do this. In such a case, the new operator gives away the control to the caller and then it is very difficult to ensure that we live up to the constraints.

The Factory Method is meant to take care of such scenarios. Essentially, Factory method is a method that takes care of instantiating the object. It contains the complexity of instantiation and any other functionality that goes along with it.

Factory method or any creational pattern does not mean that we have a good design. The Factory Method is not necessarily the best way of creating instances. The "new" operator is usually the best way of doing the job - that is why languages provide it. It is important to understand when and which creational pattern is required.

Let us now look at how the Factory Method pattern in implemented in code:

public interface Product { … }

public abstract class Creator {
	public void anOperation() 	{
		Product product = factoryMethod();
	}
	
	protected abstract Product factoryMethod();
}

public class ConcreteProduct implements Product { … }

public class ConcreteCreator extends Creator {
	protected Product factoryMethod() {
		return new ConcreteProduct();
	}
}

public class Client {
	public static void main( String arg[] ) {
		Creator creator = new ConcreteCreator();
		creator.anOperation();
	}
}