165
votes

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)

12
There are some more nice answers here. softwareengineering.stackexchange.com/questions/405688/…. The one from @Berin Loritsch , will help grasp the real strength and difference of Strategy from Factory,Nilesh Pawar

12 Answers

258
votes

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.

37
votes

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.

27
votes

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.

13
votes
  • 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.

13
votes

First of all a difference between simple factory and abstract factory must be made. The first one is a simple factory where you only have one class which acts as a factory for object creation, while in the latter you connect to an factory interface (which defines the method names) and then call the different factories that implement this interface which are supposed to have different implementations of the same method based on some criteria. For example, we have a ButtonCreationFactory interface, which is implemented by two factories, the first WindowsButtonCreationFactory (creates buttons with Windows look and feel) and the second LinuxButtonCreationFactory (creates buttons with Linux look and feel). So both these factories do have the same creation method with different implementations (algorithms). You can reference this in runtime based on the method that you type of button that you want.

For example if you want buttons with Linux look and feel:

ButtonCreationFactory myFactory = new LinuxButtonCreationFactory();
Button button1 = myFactory.createButton(...);

or if you want Windows buttons

ButtonCreationFactory myFactory = new WindowsButtonCreationFactory();
Button button1 = myFactory.createButton(...);

Exactly in this case, it results in a kind of strategy pattern, since it differentiates algorithms for doing some creation. However, it differs from it semantically because it is used for OBJECT CREATION rather than operational algorithms. So, basically with abstract factory you have object creation using different strategies, which makes it very similar to the strategy pattern. However the AbstractFactory is creational, while the Strategy pattern is operational. Implementation wise, they result to be the same.

13
votes

Factory (and FactoryMethod returned by Factory):

  1. Creational pattern
  2. Based on inheritance
  3. Factory returns a Factory Method (interface) which in turn returns Concrete Object
  4. You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
  5. Client always access interface only and you can hide object creation details in Factory method

Have a look at this wikipedia article and javarevisited article

Strategy pattern:

  1. It's a behavioural pattern
  2. It's based on delegation
  3. It changes guts of the object by modifying method behaviour
  4. It's used to switch between family of algorithms
  5. It changes the behaviour of the object at run time

Example:

You can configure Discount strategy for a particular item ( AirFare ticket or ShoppingCart item). In this example, you will offer 25% discount to an item during July - December and No discount on the item during Jaunary - June.

Related posts:

Real World Example of the Strategy Pattern

Design Patterns: Factory vs Factory method vs Abstract Factory

4
votes

Strategy pattern in simple terms is more of runtime creation of behaviour where you are not concerned with the implementing class. On the other had factory is runtime creation of concrete class instance and it is up to you to use any behaviour(method) exposed by the implemented interface.

3
votes

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

2
votes

You cannot understand the difference simply by looking at the code or categorization. To grasp the GoF patterns correctly, look for their intents:

Strategy: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

Factory Method: "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."

And here's an elaborate explanation about the intents and the differences between these two patterns: Difference between Factory Method and Strategy design patterns

1
votes

I may digress with Oscar in that his example of a Factory implementation is rather tightly coupled and very closed, no wonder your pick is Strategy pattern. A Factory implementation should not depend on any fixed number of specific classes being instantiated, For example:

public Command getCommand( int operatingSystem ) {        
   return commandTable.get(operatingSystem); 
}

...

public class WindowsCommand implements Command {
    ...
    static {
        CommandTable.getInstance().registerCommand(WIN_COMMAND_ID, new WindowsCommand());
    }

}

I guess the most appropriate criteria to choose one or another is mostly the terms you employ to name your classes and methods, taking into account we all should tend to program to interfaces and not to classes and also focus on the goal: we aim to determine which code will execute on runtime. That said, we can achieve the goal by using any of both patterns.

1
votes

Strategy and Factory are different purposes. In strategy you have the approach defined, using this pattern you can interchange the behavior (algorithms). Coming to Factory there are lot of variations around. But the original pattern from GO4 states factory leaves creation of object to child class. Here with the factory you are replacing complete instance not the behavior you are interested in. By this you will be replacing complete system not the algorithm.

1
votes

Factory pattern is a creational pattern, which is created with specified properties(behaviour). while at run time after creation u cn't change it's properties(behaviour). so if u need different properties(behaviour) u have to delete the object and create new object with needed properties(behaviour). which is not gud. while in case of strategy pattern u can change the properties(behaviour) at run time.