What is the difference between Factory and Strategy patterns?

Sappidireddy picture Sappidireddy · Mar 5, 2009 · Viewed 56.2k times · Source

Can any one explain the difference between factory and strategy patterns?

For me both are looking same other than an extra factory class (which create an object of product in factory patterns)

Answer

tvanfosson picture tvanfosson · Mar 5, 2009

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.