In computer programming, the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime. In Software engineering, a design pattern is a general reusable solution to a commonly occurring problem in Software design. In Mathematics, Computing, Linguistics and related subjects an algorithm is a sequence of finite instructions often used for Calculation
In some programming languages, such as those without polymorphism, the issues addressed by this pattern are handled through forms of reflection, such as the native function pointer or function delegate syntax. In Computer science, polymorphism is a Programming language feature that allows values of different Data types to be handled using a In Computer science, reflection is the process by which a Computer program can observe and modify its own structure and behavior In Object-oriented programming there are two related notions of delegation.
This pattern is invisible in languages with first-class functions. In Computer science, a Programming language is said to support first-class functions (or function literal) if it treats functions as See the Python code for an example.
The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
Contents |
![]()
package wikipedia. patterns. strategy; //StrategyExample test application public class StrategyExample { public static void main(String[] args) { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyA()); context. execute(); context = new Context(new ConcreteStrategyB()); context. execute(); context = new Context(new ConcreteStrategyC()); context. execute(); } } // The classes that implement a concrete strategy should implement this // The context class uses this to call the concrete strategy interface IStrategy { void execute(); } // Implements the algorithm using the strategy interface class ConcreteStrategyA implements IStrategy { public void execute() { System. out. println( "Called ConcreteStrategyA. execute()" ); } } class ConcreteStrategyB implements IStrategy { public void execute() { System. out. println( "Called ConcreteStrategyB. execute()" ); } } class ConcreteStrategyC implements IStrategy { public void execute() { System. out. println( "Called ConcreteStrategyC. execute()" ); } } // Configured with a ConcreteStrategy object and maintains a reference to a Strategy object class Context { IStrategy strategy; // Constructor public Context(IStrategy strategy) { this. strategy = strategy; } public void execute() { this. strategy. execute(); } }
Python has first-class functions, so there's no need to implement this pattern explicitly. Python is a general-purpose High-level programming language. Its design philosophy emphasizes programmer productivity and code readability In Computer science, a Programming language is said to support first-class functions (or function literal) if it treats functions as However one loses information because the interface of the strategy is not made explicit. Here's an example you might encounter in GUI programming, using a callback function:
class Button: """A very basic button widget. """ def __init__(self, submit_func, label): self. on_submit = submit_func # Set the strategy function directly self. label = label # Create two instances with different strategies button1 = Button(sum, "Add 'em") button2 = Button(lambda nums: " ". join(map(str, nums)), "Join 'em") # Test each button numbers = range(1, 10) # A list of numbers 1 through 9 print button1. on_submit(numbers) # displays "45" print button2. on_submit(numbers) # displays "1 2 3 4 5 6 7 8 9"
using System; namespace Wikipedia. C# (pronounced C Sharp is a Multi-paradigm Patterns. Strategy { // MainApp test application class MainApp { static void Main() { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyA()); context. Execute(); context = new Context(new ConcreteStrategyB()); context. Execute(); context = new Context(new ConcreteStrategyC()); context. Execute(); } } // The classes that implement a concrete strategy should implement this // The context class uses this to call the concrete strategy interface IStrategy { void Execute(); } // Implements the algorithm using the strategy interface class ConcreteStrategyA : IStrategy { public void Execute() { Console. WriteLine( "Called ConcreteStrategyA. Execute()" ); } } class ConcreteStrategyB : IStrategy { public void Execute() { Console. WriteLine( "Called ConcreteStrategyB. Execute()" ); } } class ConcreteStrategyC : IStrategy { public void Execute() { Console. WriteLine( "Called ConcreteStrategyC. Execute()" ); } } // Configured with a ConcreteStrategy object and maintains a reference to a Strategy object class Context { IStrategy strategy; // Constructor public Context(IStrategy strategy) { this. strategy = strategy; } public void Execute() { strategy. Execute(); } } }
//invoked from application. initialize private function init() : void { var context:Context; context = new Context( new ConcreteStrategyA() ); context. execute(); context = new Context( new ConcreteStrategyB() ); context. execute(); context = new Context( new ConcreteStrategyC() ); context. execute(); } package org. wikipedia. patterns. strategy { public interface IStrategy { function execute() : void ; } } package org. wikipedia. patterns. strategy { public final class ConcreteStrategyA implements IStrategy { public function execute():void { trace( "ConcreteStrategyA. execute(); invoked" ); } } } package org. wikipedia. patterns. strategy { public final class ConcreteStrategyB implements IStrategy { public function execute():void { trace( "ConcreteStrategyB. execute(); invoked" ); } } } package org. wikipedia. patterns. strategy { public final class ConcreteStrategyC implements IStrategy { public function execute():void { trace( "ConcreteStrategyC. execute(); invoked" ); } } } package org. wikipedia. patterns. strategy { public class Context { private var strategy:IStrategy; public function Context(strategy:IStrategy) { this. strategy = strategy; } public function execute() : void { strategy. execute(); } } }
<?php class StrategyExample { public function __construct() { $context = new Context(new ConcreteStrategyA()); $context->execute(); $context = new Context(new ConcreteStrategyB()); $context->execute(); $context = new Context(new ConcreteStrategyC()); $context->execute(); } } interface IStrategy { public function execute(); } class ConcreteStrategyA implements IStrategy { public function execute() { echo "Called ConcreteStrategyA execute method\n"; } } class ConcreteStrategyB implements IStrategy { public function execute() { echo "Called ConcreteStrategyB execute method\n"; } } class ConcreteStrategyC implements IStrategy { public function execute() { echo "Called ConcreteStrategyC execute method\n"; } } class Context { var $strategy; public function __construct(IStrategy $strategy) { $this->strategy = $strategy; } public function execute() { $this->strategy->execute(); } } new StrategyExample; ?>
The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. PHP is a computer Scripting language. Originally designed for producing Dynamic web pages it has evolved to include a Command line interface capability Unified Modeling Language ( UML) is a standardized general-purpose Modeling language in the field of Software engineering. The bridge pattern is a design pattern used in Software engineering which is meant to "decouple an abstraction from its Implementation However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure. The bridge pattern is a design pattern used in Software engineering which is meant to "decouple an abstraction from its Implementation
The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.
According to Strategy pattern, the behaviors of a class should not be inherited, instead they should be encapsulated using interfaces. As an example, consider a car class. Two possible behaviors of 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. This may not be a concern when there are only a small number of models, but 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. Specific classes encapsulate 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 run-time 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();
This gives greater flexibility in design and is in harmony with OCP (Open Closed Principle) that states classes should be open for extension but closed for modification.