views:

733

answers:

5

Can any one explain the difference between factory and strategy pattrens? for me both are looking same other than an extra factory class(which create an object of product In factory pattrens)

+10  A: 

A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner. In the classic example, a factory might create different types of Animals: Dog, Cat, Tiger, while a strategy pattern would perform particular actions, for example, Move; using Run, Walk, or Lope strategies.

In fact the two can be used together. For example, you may have a factory that creates your business objects. It may use different strategies based on the persistence medium. If your data is stored locally in XML it would use one strategy. If the data were remote in a different database, it would use another.

tvanfosson
+3  A: 

The strategy pattern allows you to polymorphically change behavior of a class.

The factory pattern allows you to encapsulate object creation.

Gary makes a great point. If you are using the principle of coding to abstractions rather than "concretions" then a lot of the patterns start looking like variations on a theme.

jlembke
+1  A: 

Just to add to what tvanfosson said, a lot of the patterns look the same as far as implementation. That is, a lot have you create an interface where perhaps there wasn't one before in your code, and then create a bunch of implementations of that interface. The difference is in their purpose and how they are used.

Gary Kephart
A: 
  • The Factory ( method ) Pattern.

Create concrete instances only. Different arguments may result in different objects. It depends on the logic etc.

  • The Strategy Pattern.

Encapsulate the algorithm ( steps ) to perform an action. So you can change the strategy and use another algorithm.

While both look like very similar, the purpose is rather different, one purpose is to create the other is to perform an action.

So. If your Factory method is fixed, you may have it like this:

 public Command getCommand( int operatingSystem ) { 
      switch( operatingSystem ) { 
           case UNIX    :
           case LINUX   : return new UnixCommand();
           case WINDOWS : return new WindowsCommand();
           case OSX     : return new OSXCommand();
       }
  }

But suppose your factory needs more advanced or dynamic creation. You may add to the factory method an strategy and change it without having to recompile, the strategy may change at runtime.

OscarRyz
A: 

To extend on what Oscar said and in reference to his code:

The getCommand is the Factory and the UnixCommand, WindowsCommand and OSXCommand classes are Strategies