Why do I require to implement Factory Design Pattern?
Let me start this with an example.
class XYZAlgorithm{
public void compute(int[] arr){
MergeSort mergeSort = new MergeSort(arr);
........
.......
}
}
So, you XYZAlgorithm class, which has a method compute(..), this method is using a MergeSort class to sort the array. MergeSort is a class provided by a vendor/ third party. well, its good. Till here, everything is fine.
But what in future, if you decide to use some other class lets say BubbleSort, instead of MergeSort? Well, edit the XYZAlgorithm.java file, change the compute() method and we are good to go. Is there anything wrong with this approach?
There are 2 things wrong with this approach?
1) If you have 100's of algorithm classes written in you project, you have to visit every class and change the code. Fragile. too much of change. Why cant I make the change at one place, and every algorithm sees it. Why do i have to worry about whats the implementing class is?
2) Recollect the first five principles of class design. Its not the work of XYZAlgorithm to care about implementation class. XYZAlgorithm should only change, if business logic changes, if its functionality changes.
Well, lets better delegate the task of selecting & creating MergeSort/ BubbleSort to some other class. This class will create an instance and handle you back the interface to class the required method of MergeSort/ BubbleSort. So, in future, if you decide to use some other class, just change the factory class and you are good to go.
class XYZAlgorithm{
public void compute(int[] arr){
Sort sort = Factory.getInstance();
........
.......
}
}
interface Sort{
void sort();
}
class Factory{
static Sort getInstance(){
//return new MergeSort();
return new BubbleSort();
}
}
class MergeSort implements Sort{
void sort(){
}
}
class BubbleSort implements Sort{
void sort(){
}
}
No comments:
Post a Comment