Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Strategy pattern
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{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 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=[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 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 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 == === 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.<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]] [[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. The <code>Strategy1</code> and <code>Strategy2</code> classes implement the <code>Strategy</code> interface, that is, implement (encapsulate) an algorithm. <br> The [[Unified Modeling Language|UML]] [[sequence diagram]] 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>. Thereafter, <code>Context</code> changes its strategy and calls <code>algorithm()</code> on a <code>Strategy2</code> object, which performs the algorithm and returns the result to <code>Context</code>. === Class diagram === [[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 LePUS3 ([http://lepus.org.uk/ref/legend/legend.xml legend])]] <!--== 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 --> == Strategy and open/closed principle == [[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. 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 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(); </syntaxhighlight> <syntaxhighlight lang="java"> /* 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" } } </syntaxhighlight> ==See also== * [[Dependency injection]] * [[Higher-order function]] * [[List of object-oriented programming terms]] * [[Mixin]] * [[Policy-based design]] * [[Type class]] * [[Entity–component–system]] * [[Composition over inheritance]] ==References== {{Commonscat|Strategy (design pattern)}} {{Reflist}} ==External links== {{wikibooks|Computer Science Design Patterns|Strategy|Strategy implementations in various languages}} * [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://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}} [[Category:Software design patterns]] [[Category:Articles with example C Sharp code]] [[Category:Articles with example Java code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite web
(
edit
)
Template:Commonscat
(
edit
)
Template:Design Patterns Patterns
(
edit
)
Template:ISBN
(
edit
)
Template:In lang
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Sister project
(
edit
)
Template:Webarchive
(
edit
)
Template:Wikibooks
(
edit
)