I start learning Design Patterns. Now I understand a little bit but there are quite a lot of confusions for me. What's the difference between Strategy DP and Factory Method DP? For me they both looks like the same.
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.
But, the key difference is that Strategy Pattern is about modifying a behaviour of a context in runtime using strategies, while Template Method Pattern is about following a skeleton implementation of an algorithm and modifying its behaviour by overriding methods of the skeleton class in the subclasses.
The factory method pattern is a software design pattern but the simple factory is like a programming idiom. The factory method pattern provides an abstraction/interface for creating an object. And the job must be done by a subclass. A Factory class decides an object's instantiation in a subclass.
Design Patterns are categorized mainly into three categories: Creational Design Pattern, Structural Design Pattern, and Behavioral Design Pattern.
Strategy is about behavior. Factory is about creation/instatation.
Suppose you have an algorithm, to calculate a discount percentage. You can have 2 implementations of that algorithm; one for regular customers, and one for extra-ordinary good customers.
You can use a strategy DP for this implementation: you create an interface, and 2 classes that implement that interface. In one class, you implement the regular discount-calculation algorithm, in the other class you implement the 'good customers' algorithm.
Then, you can use a factory pattern to instantiate the class that you want. The factory method thus instantiates either the regular customer-discount algorithm, or the other implementation.
In short: the factory method instantiates the correct class; the strategy implementation contains the algorithm that must be executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With