Strategy pattern: Difference between revisions
Bluelinking 1 books for verifiability.) #IABot (v2.1alpha3 |
Loymdayddaud (talk | contribs) →Structure: Spacing fix Tags: Mobile edit Mobile web edit |
||
(43 intermediate revisions by 33 users not shown) | |||
Line 1: | Line 1: | ||
{{short description|Software design pattern}} |
|||
In [[computer programming]], the '''strategy pattern''' (also known as the '''policy pattern''') is a [[behavioral design pattern|behavioral]] [[design pattern (computer science)|software design pattern]] that enables selecting an [[algorithm]] at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.<ref>{{cite web|title=The Strategy design pattern - Problem, Solution, and Applicability|url=http://w3sdesign.com/?gr=b09&ugr=proble|website=w3sDesign.com|accessdate=2017-08-12}}</ref> |
|||
In [[computer programming]], the '''strategy pattern''' (also known as the '''policy pattern''') is a [[behavioral design pattern|behavioral]] [[design pattern (computer science)|software design pattern]] that enables selecting an [[algorithm]] at runtime. Instead of implementing a single algorithm directly, code receives runtime instructions as to which in a family of algorithms to use.<ref>{{cite web|title=The Strategy design pattern - Problem, Solution, and Applicability|url=http://w3sdesign.com/?gr=b09&ugr=proble|website=w3sDesign.com|access-date=2017-08-12}}</ref> |
|||
Strategy lets the algorithm vary independently from clients that use it.<ref>Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates, ''Head First Design Patterns'', First Edition, Chapter 1, Page 24, O'Reilly Media, Inc, 2004. {{ISBN|978-0-596-00712-6}}</ref> Strategy is one of the patterns included in the influential book ''[[Design Patterns]]'' by Gamma et al.<ref name="GoF">{{cite book|author=Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides|title=Design Patterns: Elements of Reusable Object-Oriented Software|year=1994|publisher=Addison Wesley|isbn=0-201-63361-2|pages=315ff|url-access=registration|url=https://archive.org/details/designpatternsel00gamm}}</ref> that popularized the concept of using design patterns to describe how to design flexible and reusable object-oriented software. Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable. |
Strategy lets the algorithm vary independently from clients that use it.<ref>Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates, ''Head First Design Patterns'', First Edition, Chapter 1, Page 24, O'Reilly Media, Inc, 2004. {{ISBN|978-0-596-00712-6}}</ref> Strategy is one of the patterns included in the influential book ''[[Design Patterns]]'' by Gamma et al.<ref name="GoF">{{cite book|author=Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides|title=Design Patterns: Elements of Reusable Object-Oriented Software|year=1994|publisher=Addison Wesley|isbn=0-201-63361-2|pages=[https://archive.org/details/designpatternsel00gamm/page/315 315ff]|url-access=registration|url=https://archive.org/details/designpatternsel00gamm/page/315}}</ref> that popularized the concept of using design patterns to describe how to design flexible and reusable object-oriented software. Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable. |
||
For instance, a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known until |
For instance, a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known until runtime and may require radically different validation to be performed. The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without [[Duplicate code|code duplication]]. |
||
Typically the strategy pattern stores a reference to |
Typically, the strategy pattern stores a reference to code in a data structure and retrieves it. This can be achieved by mechanisms such as the native [[function pointer]], the [[first-class function]], classes or class instances in [[object-oriented programming]] languages, or accessing the language implementation's internal storage of code via [[Reflection (computer science)|reflection]]. |
||
== Structure == |
== Structure == |
||
=== UML class and sequence diagram === |
=== UML class and sequence diagram === |
||
[[File:w3sDesign Strategy Design Pattern UML.jpg|frame|none|A sample UML class and sequence diagram for the Strategy design pattern. |
[[File:w3sDesign Strategy Design Pattern UML.jpg|frame|none|A sample UML class and sequence diagram for the Strategy design pattern.<ref>{{cite web|title=The Strategy design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=b09&ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}</ref>]] |
||
In the above [[Unified Modeling Language|UML]] [[ |
In the above [[Unified Modeling Language|UML]] [[class diagram]], the <code>Context</code> class does not implement an algorithm directly. |
||
Instead, <code>Context</code> refers to the <code>Strategy</code> interface for performing an algorithm (<code>strategy.algorithm()</code>), which makes <code>Context</code> independent of how an algorithm is implemented. |
Instead, <code>Context</code> refers to the <code>Strategy</code> interface for performing an algorithm (<code>strategy.algorithm()</code>), which makes <code>Context</code> independent of how an algorithm is implemented. |
||
The <code>Strategy1</code> and <code>Strategy2</code> classes implement the <code>Strategy</code> interface, that is, implement (encapsulate) an algorithm. |
The <code>Strategy1</code> and <code>Strategy2</code> classes implement the <code>Strategy</code> interface, that is, implement (encapsulate) an algorithm. |
||
<br> |
<br> |
||
The [[Unified Modeling Language|UML]] [[ |
The [[Unified Modeling Language|UML]] [[sequence diagram]] |
||
shows the |
shows the runtime interactions: The <code>Context</code> object delegates an algorithm to different <code>Strategy</code> objects. First, <code>Context</code> calls <code>algorithm()</code> on a <code>Strategy1</code> object, |
||
which performs the algorithm and returns the result to <code>Context</code>. |
which performs the algorithm and returns the result to <code>Context</code>. |
||
Thereafter, <code>Context</code> changes its strategy and calls <code>algorithm()</code> on a <code>Strategy2</code> object, |
Thereafter, <code>Context</code> changes its strategy and calls <code>algorithm()</code> on a <code>Strategy2</code> object, |
||
Line 21: | Line 22: | ||
=== Class diagram === |
=== Class diagram === |
||
[[Image:Strategy Pattern in UML.png|thumb|none|350px|Strategy Pattern in [[Unified Modeling Language|UML]] ]]<ref>http://www.mcdonaldland.info/2007/11/28/40/</ref> |
[[Image:Strategy Pattern in UML.png|thumb|none|350px|Strategy Pattern in [[Unified Modeling Language|UML]] ]]<ref>{{cite web | url=http://www.mcdonaldland.info/2007/11/28/40/ | title=Design Patterns Quick Reference – McDonaldLand }}</ref> |
||
[[Image:Strategy pattern in LePUS3.gif|thumb|none|400px|Strategy pattern in |
[[Image:Strategy pattern in LePUS3.gif|thumb|none|400px|Strategy pattern in LePUS3 |
||
([http://lepus.org.uk/ref/legend/legend.xml legend])]] |
([http://lepus.org.uk/ref/legend/legend.xml legend])]] |
||
== Example == |
<!--== Example == |
||
Wikipedia is not a list of examples. Do not add examples from your favorite programming language here; this page exists to explain the design pattern, not to show how it interacts with subtleties of every language under the sun. Feel free to add examples here: http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Strategy --> |
|||
=== C# === |
|||
The following example is in [[C Sharp (programming language)|C#]]. |
|||
<source lang="C#" line="1"> |
|||
public class StrategyPatternWiki |
|||
{ |
|||
public static void Main(String[] args) |
|||
{ |
|||
// Prepare strategies |
|||
IBillingStrategy normalStrategy = new NormalStrategy(); |
|||
IBillingStrategy happyHourStrategy = new HappyHourStrategy(); |
|||
Customer firstCustomer = new Customer(normalStrategy); |
|||
// Normal billing |
|||
firstCustomer.Add(1.0, 1); |
|||
// Start Happy Hour |
|||
firstCustomer.Strategy = happyHourStrategy; |
|||
firstCustomer.Add(1.0, 2); |
|||
// New Customer |
|||
Customer secondCustomer = new Customer(happyHourStrategy); |
|||
secondCustomer.Add(0.8, 1); |
|||
// The Customer pays |
|||
firstCustomer.PrintBill(); |
|||
// End Happy Hour |
|||
secondCustomer.Strategy = normalStrategy; |
|||
secondCustomer.Add(1.3, 2); |
|||
secondCustomer.Add(2.5, 1); |
|||
secondCustomer.PrintBill(); |
|||
} |
|||
} |
|||
class Customer |
|||
{ |
|||
private IList<double> drinks; |
|||
// Get/Set Strategy |
|||
public IBillingStrategy Strategy { get; set; } |
|||
public Customer(IBillingStrategy strategy) |
|||
{ |
|||
this.drinks = new List<double>(); |
|||
this.Strategy = strategy; |
|||
} |
|||
public void Add(double price, int quantity) |
|||
{ |
|||
this.drinks.Add(this.Strategy.GetActPrice(price * quantity)); |
|||
} |
|||
// Payment of bill |
|||
public void PrintBill() |
|||
{ |
|||
double sum = 0; |
|||
foreach (double i in this.drinks) |
|||
{ |
|||
sum += i; |
|||
} |
|||
Console.WriteLine("Total due: " + sum); |
|||
this.drinks.Clear(); |
|||
} |
|||
} |
|||
interface IBillingStrategy |
|||
{ |
|||
double GetActPrice(double rawPrice); |
|||
} |
|||
// Normal billing strategy (unchanged price) |
|||
class NormalStrategy : IBillingStrategy |
|||
{ |
|||
public double GetActPrice(double rawPrice) |
|||
{ |
|||
return rawPrice; |
|||
} |
|||
} |
|||
// Strategy for Happy hour (50% discount) |
|||
class HappyHourStrategy : IBillingStrategy |
|||
{ |
|||
public double GetActPrice(double rawPrice) |
|||
{ |
|||
return rawPrice * 0.5; |
|||
} |
|||
} |
|||
</source> |
|||
=== Java === |
|||
The following example is in [[Java (programming language)|Java]]. |
|||
<source lang="java"> |
|||
import java.util.ArrayList; |
|||
@FunctionalInterface |
|||
interface BillingStrategy { |
|||
// Use a price in cents to avoid floating point round-off error |
|||
int getActPrice(int rawPrice); |
|||
// Normal billing strategy (unchanged price) |
|||
static BillingStrategy normalStrategy() { |
|||
return rawPrice -> rawPrice; |
|||
} |
|||
// Strategy for Happy hour (50% discount) |
|||
static BillingStrategy happyHourStrategy() { |
|||
return rawPrice -> rawPrice / 2; |
|||
} |
|||
} |
|||
class Customer { |
|||
private final ArrayList<Integer> drinks = new ArrayList<>(); |
|||
private BillingStrategy strategy; |
|||
public Customer(BillingStrategy strategy) { |
|||
this.strategy = strategy; |
|||
} |
|||
public void add(int price, int quantity) { |
|||
this.drinks.add(this.strategy.getActPrice(price*quantity)); |
|||
} |
|||
// Payment of bill |
|||
public void printBill() { |
|||
int sum = this.drinks.stream().mapToInt(v -> v).sum(); |
|||
System.out.println("Total due: " + sum / 100.0); |
|||
this.drinks.clear(); |
|||
} |
|||
// Set Strategy |
|||
public void setStrategy(BillingStrategy strategy) { |
|||
this.strategy = strategy; |
|||
} |
|||
} |
|||
public class StrategyPattern { |
|||
public static void main(String[] arguments) { |
|||
// Prepare strategies |
|||
BillingStrategy normalStrategy = BillingStrategy.normalStrategy(); |
|||
BillingStrategy happyHourStrategy = BillingStrategy.happyHourStrategy(); |
|||
Customer firstCustomer = new Customer(normalStrategy); |
|||
// Normal billing |
|||
firstCustomer.add(100, 1); |
|||
// Start Happy Hour |
|||
firstCustomer.setStrategy(happyHourStrategy); |
|||
firstCustomer.add(100, 2); |
|||
// New Customer |
|||
Customer secondCustomer = new Customer(happyHourStrategy); |
|||
secondCustomer.add(80, 1); |
|||
// The Customer pays |
|||
firstCustomer.printBill(); |
|||
// End Happy Hour |
|||
secondCustomer.setStrategy(normalStrategy); |
|||
secondCustomer.add(130, 2); |
|||
secondCustomer.add(250, 1); |
|||
secondCustomer.printBill(); |
|||
} |
|||
} |
|||
</source> |
|||
<!-- |
|||
Wikipedia is not a list of examples. Do not add examples from your favorite programming language here; this page exists to explain the design pattern, not to show how it interacts with subtleties of every language under the sun. Feel free to add examples here: http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Strategy --> |
|||
== Strategy and open/closed principle == |
== Strategy and open/closed principle == |
||
[[Image:StrategyPattern IBrakeBehavior.svg|thumb|400px|Accelerate and [[brake]] behaviors must be declared in each new [[car model]].]] |
[[Image:StrategyPattern IBrakeBehavior.svg|thumb|400px|Accelerate and [[brake]] behaviors must be declared in each new [[car model]].]] |
||
According to the strategy pattern, the behaviors of a class should not be inherited. Instead they should be encapsulated using interfaces. This is compatible with the [[open/closed principle]] (OCP), which proposes that classes should be open for extension but closed for modification. |
According to the strategy pattern, the behaviors of a class should not be inherited. Instead, they should be encapsulated using interfaces. This is compatible with the [[open/closed principle]] (OCP), which proposes that classes should be open for extension but closed for modification. |
||
As an example, consider a car class. Two possible functionalities for car are ''brake'' and ''accelerate''. Since accelerate and brake behaviors change frequently between models, a common approach is to implement these behaviors in subclasses. This approach has significant drawbacks |
As an example, consider a car class. Two possible functionalities for car are ''brake'' and ''accelerate''. Since accelerate and brake behaviors change frequently between models, a common approach is to implement these behaviors in subclasses. This approach has significant drawbacks; accelerate and brake behaviors must be declared in each new car model. The work of managing these behaviors increases greatly as the number of models increases, and requires code to be duplicated across models. Additionally, it is not easy to determine the exact nature of the behavior for each model without investigating the code in each. |
||
The strategy pattern uses [[composition over inheritance|composition instead of inheritance]]. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at |
The strategy pattern uses [[composition over inheritance|composition instead of inheritance]]. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at runtime as well as at design-time. For instance, a car object's brake behavior can be changed from <code>BrakeWithABS()</code> to <code>Brake()</code> by changing the <code>brakeBehavior</code> member to: |
||
< |
<syntaxhighlight lang="cpp"> |
||
brakeBehavior = new Brake(); |
brakeBehavior = new Brake(); |
||
</syntaxhighlight> |
|||
</source> |
|||
< |
<syntaxhighlight lang="java"> |
||
/* Encapsulated family of Algorithms |
/* Encapsulated family of Algorithms |
||
Line 278: | Line 108: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</source> |
|||
==See also== |
==See also== |
||
Line 295: | Line 125: | ||
==External links== |
==External links== |
||
* [http://design-patterns-with-uml.blogspot.com.ar/2013/02/strategy-pattern.html Strategy Pattern in UML (Spanish, but english model)] |
|||
{{wikibooks|Computer Science Design Patterns|Strategy|Strategy implementations in various languages}} |
{{wikibooks|Computer Science Design Patterns|Strategy|Strategy implementations in various languages}} |
||
* [http:// |
* [http://design-patterns-with-uml.blogspot.com.ar/2013/02/strategy-pattern.html Strategy Pattern in UML] {{in lang|es}} |
||
* {{cite web |last1=Geary |first1=David |date=2002-04-26 |df=mdy |url=https://www.infoworld.com/article/2074195/strategy-for-success.html |title=Strategy for success |department=Java Design Patterns |work=[[JavaWorld]] |access-date=2020-07-20}} |
|||
* [http://www.adamtornhill.com/Patterns%20in%20C%203,%20STRATEGY.pdf Strategy Pattern for C article] |
* [http://www.adamtornhill.com/Patterns%20in%20C%203,%20STRATEGY.pdf Strategy Pattern for C article] |
||
* [http://www.lepus.org.uk/ref/companion/Strategy.xml Strategy pattern in UML and in LePUS3] (a formal modelling notation) |
|||
* [http://martinfowler.com/refactoring/catalog/replaceTypeCodeWithStateStrategy.html Refactoring: Replace Type Code with State/Strategy] |
* [http://martinfowler.com/refactoring/catalog/replaceTypeCodeWithStateStrategy.html Refactoring: Replace Type Code with State/Strategy] |
||
* |
* {{webarchive |url=https://web.archive.org/web/20170415154927/http://www.aleccove.com/2016/02/the-strategy-pattern-in-javascript |title=The Strategy Design Pattern}} Implementation of the Strategy pattern in JavaScript |
||
{{Design Patterns Patterns}} |
{{Design Patterns Patterns}} |
Latest revision as of 03:59, 8 September 2024
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives runtime instructions as to which in a family of algorithms to use.[1]
Strategy lets the algorithm vary independently from clients that use it.[2] Strategy is one of the patterns included in the influential book Design Patterns by Gamma et al.[3] that popularized the concept of using design patterns to describe how to design flexible and reusable object-oriented software. Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable.
For instance, a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known until runtime and may require radically different validation to be performed. The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.
Typically, the strategy pattern stores a reference to code in a data structure and retrieves it. This can be achieved by mechanisms such as the native function pointer, the first-class function, classes or class instances in object-oriented programming languages, or accessing the language implementation's internal storage of code via reflection.
Structure
[edit]UML class and sequence diagram
[edit]In the above UML class diagram, the Context
class does not implement an algorithm directly.
Instead, Context
refers to the Strategy
interface for performing an algorithm (strategy.algorithm()
), which makes Context
independent of how an algorithm is implemented.
The Strategy1
and Strategy2
classes implement the Strategy
interface, that is, implement (encapsulate) an algorithm.
The UML sequence diagram
shows the runtime interactions: The Context
object delegates an algorithm to different Strategy
objects. First, Context
calls algorithm()
on a Strategy1
object,
which performs the algorithm and returns the result to Context
.
Thereafter, Context
changes its strategy and calls algorithm()
on a Strategy2
object,
which performs the algorithm and returns the result to Context
.
Class diagram
[edit]
Strategy and open/closed principle
[edit]According to the strategy pattern, the behaviors of a class should not be inherited. Instead, they should be encapsulated using interfaces. This is compatible with the open/closed principle (OCP), which proposes that classes should be open for extension but closed for modification.
As an example, consider a car class. Two possible functionalities for car are brake and accelerate. Since accelerate and brake behaviors change frequently between models, a common approach is to implement these behaviors in subclasses. This approach has significant drawbacks; accelerate and brake behaviors must be declared in each new car model. The work of managing these behaviors increases greatly as the number of models increases, and requires code to be duplicated across models. Additionally, it is not easy to determine the exact nature of the behavior for each model without investigating the code in each.
The strategy pattern uses composition instead of inheritance. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at runtime as well as at design-time. For instance, a car object's brake behavior can be changed from BrakeWithABS()
to Brake()
by changing the brakeBehavior
member to:
brakeBehavior = new Brake();
/* Encapsulated family of Algorithms
* Interface and its implementations
*/
public interface IBrakeBehavior {
public void brake();
}
public class BrakeWithABS implements IBrakeBehavior {
public void brake() {
System.out.println("Brake with ABS applied");
}
}
public class Brake implements IBrakeBehavior {
public void brake() {
System.out.println("Simple Brake applied");
}
}
/* Client that can use the algorithms above interchangeably */
public abstract class Car {
private IBrakeBehavior brakeBehavior;
public Car(IBrakeBehavior brakeBehavior) {
this.brakeBehavior = brakeBehavior;
}
public void applyBrake() {
brakeBehavior.brake();
}
public void setBrakeBehavior(IBrakeBehavior brakeType) {
this.brakeBehavior = brakeType;
}
}
/* Client 1 uses one algorithm (Brake) in the constructor */
public class Sedan extends Car {
public Sedan() {
super(new Brake());
}
}
/* Client 2 uses another algorithm (BrakeWithABS) in the constructor */
public class SUV extends Car {
public SUV() {
super(new BrakeWithABS());
}
}
/* Using the Car example */
public class CarExample {
public static void main(final String[] arguments) {
Car sedanCar = new Sedan();
sedanCar.applyBrake(); // This will invoke class "Brake"
Car suvCar = new SUV();
suvCar.applyBrake(); // This will invoke class "BrakeWithABS"
// set brake behavior dynamically
suvCar.setBrakeBehavior( new Brake() );
suvCar.applyBrake(); // This will invoke class "Brake"
}
}
See also
[edit]- Dependency injection
- Higher-order function
- List of object-oriented programming terms
- Mixin
- Policy-based design
- Type class
- Entity–component–system
- Composition over inheritance
References
[edit]- ^ "The Strategy design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-12.
- ^ Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates, Head First Design Patterns, First Edition, Chapter 1, Page 24, O'Reilly Media, Inc, 2004. ISBN 978-0-596-00712-6
- ^ Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 315ff. ISBN 0-201-63361-2.
{{cite book}}
: CS1 maint: multiple names: authors list (link) - ^ "The Strategy design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.
- ^ "Design Patterns Quick Reference – McDonaldLand".
External links
[edit]- Strategy Pattern in UML (in Spanish)
- Geary, David (April 26, 2002). "Strategy for success". Java Design Patterns. JavaWorld. Retrieved 2020-07-20.
- Strategy Pattern for C article
- Refactoring: Replace Type Code with State/Strategy
- The Strategy Design Pattern at the Wayback Machine (archived 2017-04-15) Implementation of the Strategy pattern in JavaScript