What is the difference between Factory and Strategy patterns? What is the difference between Factory and Strategy patterns? java java

What is the difference between Factory and Strategy patterns?


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.


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.


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.