Search code examples
design-patternsstrategy-patternabstract-factory

What is the diffrence between strategy design pattern and abstract factory pattern?


Can someone once and for all explain to me the difference between these two and try to give a sort of guideline for when to use each one of them? Examples would be really nice.


Solution

  • Strategy is a workaround for languages that don't have first-class functions. You pass in a strategy object that decides some policy that you want separated from the rest of the code. Think of sorting in Java and how they use Comparators, a Comparator is a strategy object that allows you to specify the policy for sorting separately from the sorting algorithm. That allows you to reuse the code by dropping in different strategies.

    Abstract Factory is an object used to create other objects, with the abstract part being that you have a factory that returns an implementation of the factory, where users of the factory access it through an interface. So one factory implementation can be swapped out for another with no changes to users of the factories, because those users are depending on the objects' interfaces only.