Dofactory.com
Dofactory.com
 Back to list
Views:   22.1K
Replies:  1
Archived

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...
Imran Khan, Aug 06, 2010
Reply 1
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.Add("Samual");

      studentRecords.Add("Jimmy");

     

      studentRecords.SetSortStrategy(new QuickSort());

      studentRecords.Sort();

 

      studentRecords.SetSortStrategy(new ShellSort());

      studentRecords.Sort();

 

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.


studentRecords.SetSortStrategy(algo);

....................

......................


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


Regards,

Rajesh Pillai




Rajesh Pillai, Aug 06, 2010
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.