Factory method comes under creational design pattern.
It provides an abstraction to instantiate one of the available
subclasses based on user input. It defers the class instantiation to subclasses.
Behaviour & Advantages
Lets the subclasses decide which class to instantiate.
Connects parallel classes exhibiting the same behavior.
We can parameterize factory method if needed.
Decouples or hides concrete classes from client. That is if a particular implementation
changes or given a new implementation all together, no need to change the client code.
Gives fine control to provide a default implementation if the user requested
implementation is not available.
In this example we have created a sort algorithm factory which instantiates one of the available
sort algorithms based on user input. User doesn't need to know the actual implementation class.
However we can hint the factory what type of algorithm we are expecting by passing
a short name of algorithm.
public class QuickSort implements ISortAlgorithm {
@Override public void sort(int[] list) {
//Dummy implementation
Arrays.sort(list);
System.out.println("Sorted using Quick Sort Algorithm : " + Arrays.toString(list));
}
}
SortFactory internally maintains a static map, algorithmMap which contains
short name for algorithm as key and implementation class as value. If we want to
support other algorithms, we need to populate this map accordingly.
If the user provided algorithmName doesn't match with any available algorithms
then we may choose to instantiate a default implementation of algorithm such as quick sort
or throw an exception saying no such algorithm available. This enhancement is left as an
exercise to readers.
Here if we observe client code just deals with ISortAlgorithm and SortFactory.
It doesn't need to know the actual implementation class. This decouples the client from
actual implementation. So we can bring in more algorithms easily.
Factory usage is shown below,