Strategy pattern is a behavioral pattern that lets the algorithm vary independently from clients that use it by defining a family of algorithms, encapsulate each one, and make them interchangeable. An algorithm that's encapsulated in this way is called a strategy. Strategy is concerned with changing the behavior of an object. source: GoF overviewIn strategy design pattern, each context object encapsulates (has) a concrete strategy object (algorithm/behavior) that is interchangeable which decides a particular way of processing request. There should be no switch statement inside Strategy. Move the switches out of Strategy class. You can apply strategy pattern to modularize your code so that big switch and all business logic are not all mixed up in the same place. However, strategy isn't a magic anti-switch solution. The strategy classes conform to the same algorithm/behavior interface, usually defined with one method (e.g. offers a method named execute() or calculate(), etc.). A request to context object will be delegated to call the encapsulated strategy object’s algorithm/behavior (e.g. execute() or calculate()) method. A strategy class encapsulates an action, not a thing. Think of Strategy pattern as a verb, or a noun that describe an action. So it wouldn't make a lot of sense to keep state in it. Therefore, the strategy implementations themselves are stateless. strategy design pattern code sample// Strategy base when to use strategy design pattern
comparisonBridge vs. Strategy (very similar)
State vs. Strategy
Flyweight vs. Strategy
references
0 Comments
Leave a Reply. |
Categories
All
Archives
May 2020
|