Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Strategy and Factory design pattern?

When I observe closely to Strategy and Factory design patterns Its almost looks similar. We can achieve the solution with any one of these patterns. Then I wanted to know when to use what.

like image 822
Mallikarjuna Sangisetty Avatar asked Sep 28 '22 19:09

Mallikarjuna Sangisetty


1 Answers

The Abstract Factory design pattern is used to solve problems like:
- How can a system be independent of how its objects are created?
- How can the way the objects are created be changed independently
(without having to change existing classes)?

The key idea in this pattern is to abstract the process of object creation.
Clients (that need to create objects) refer to an abstraction (interface) and are independent of an implementation (how the objects are created / which concrete classes are instantiated).

When not to use Abstract Factory: Object creation that does not change (when the concrete classes that get instantiated never change).

The Strategy design pattern is used to solve problems like:
- How can an object support using different algorithms
so that which algorithm to use can be selected and changed dynamically?
- And how can the way an algorithm is implemented be changed independently
(without having to change existing classes)?

For example, calculating prices in an order processing system.
To calculate prices in different ways, it should be possible to support different pricing algorithms so that which algorithm to use can be selected and changed dynamically at run-time.

The key idea in this pattern is to decouple an algorithm (that changes) from its context (and encapsulate it in a separate object).

For further discussion see the GoF Design Patterns Memory for learning object-oriented design & programming at http://w3sdesign.com.

like image 74
GFranke Avatar answered Dec 31 '22 20:12

GFranke