Home  /  Questions  /  Question

275   99.7
Aug 06, 2010

Difference between Strategy Pattern and Factory Pattern?

Is there any major difference between Strategy Pattern and Factory Pattern?  As for me its look alike and I am a bit confused which to use when. I see that the Factory Pattern gets me the object of desired type which we can also achieve using Strategy Pattern...

1,364   100.0
Aug 06, 2010
Yes, they seem to be same but they do have a visible difference.  Factory's sole purpose is to create objects and strategy's sole intent to is to provide a mechanism to select different algorithm.

You can use "factory" to create objects of "strategy".  For. e.g. take the following example from dofactory for strategy..

SortedList studentRecords = new SortedList();





      studentRecords.SetSortStrategy(new QuickSort());



      studentRecords.SetSortStrategy(new ShellSort());



Now note here, the type passed in the "SetSortStrategy" method is "hardcoded" and this will be a fragile design if this is some kind of production code.

To make this more resilent to change introduce factory (this is a crude example and is only for demonstration purpose)

SortStrategy  algo = SortFactory.GetQuickSort();  //  something like this... the actual instance creation of quicksort is controlled by the SortFactory and this is well abstracted from the client.




Let me know whether this is useful or you need more clarifications.


Rajesh Pillai

Thanks Rajesh.. I got the concept... --- Imran Khan  Aug 08, 2010
Good Example --- Subramanian Palanikumar  Oct 11, 2010