// The strategy interface declares operations common to all // supported versions of some algorithm. The context uses this // interface to call the algorithm defined by the concrete // strategies. interfaceStrategy is method execute(a, b)
// Concrete strategies implement the algorithm while following // the base strategy interface. The interface makes them // interchangeable in the context. classConcreteStrategyAddimplementsStrategy is method execute(a, b) is return a + b
classConcreteStrategySubtractimplementsStrategy is method execute(a, b) is return a - b
classConcreteStrategyMultiplyimplementsStrategy is method execute(a, b) is return a * b
// The context defines the interface of interest to clients. classContext is // The context maintains a reference to one of the strategy // objects. The context doesn't know the concrete class of a // strategy. It should work with all strategies via the // strategy interface. private strategy: Strategy
// Usually the context accepts a strategy through the // constructor, and also provides a setter so that the // strategy can be switched at runtime. method setStrategy(Strategy strategy) is this.strategy = strategy
// The context delegates some work to the strategy object // instead of implementing multiple versions of the // algorithm on its own. method executeStrategy(int a, int b) is return strategy.execute(a, b)
// The client code picks a concrete strategy and passes it to // the context. The client should be aware of the differences // between strategies in order to make the right choice. classExampleApplication is method main() is Create context object.
Read first number. Read last number. Read the desired action from user input.
if (action == addition) then context.setStrategy(newConcreteStrategyAdd())
if (action == subtraction) then context.setStrategy(newConcreteStrategySubtract())
if (action == multiplication) then context.setStrategy(newConcreteStrategyMultiply())
result = context.executeStrategy(First number, Second number)
from __future__ import annotations from abc import ABC, abstractmethod from typing importList
classContext(): """ The Context defines the interface of interest to clients. """
def__init__(self, strategy: Strategy) -> None: """ Usually, the Context accepts a strategy through the constructor, but also provides a setter to change it at runtime. """
self._strategy = strategy
@property defstrategy(self) -> Strategy: """ The Context maintains a reference to one of the Strategy objects. The Context does not know the concrete class of a strategy. It should work with all strategies via the Strategy interface. """
return self._strategy
@strategy.setter defstrategy(self, strategy: Strategy) -> None: """ Usually, the Context allows replacing a Strategy object at runtime. """
self._strategy = strategy
defdo_some_business_logic(self) -> None: """ The Context delegates some work to the Strategy object instead of implementing multiple versions of the algorithm on its own. """
# ...
print("Context: Sorting data using the strategy (not sure how it'll do it)") result = self._strategy.do_algorithm(["a", "b", "c", "d", "e"]) print(",".join(result))
# ...
classStrategy(ABC): """ The Strategy interface declares operations common to all supported versions of some algorithm. The Context uses this interface to call the algorithm defined by Concrete Strategies. """
""" Concrete Strategies implement the algorithm while following the base Strategy interface. The interface makes them interchangeable in the Context. """
if __name__ == "__main__": # The client code picks a concrete strategy and passes it to the context. # The client should be aware of the differences between strategies in order # to make the right choice.
context = Context(ConcreteStrategyA()) print("Client: Strategy is set to normal sorting.") context.do_some_business_logic() print()
print("Client: Strategy is set to reverse sorting.") context.strategy = ConcreteStrategyB() context.do_some_business_logic()
Output.txt: Execution result
1 2 3 4 5 6 7 8
Client: Strategy is set to normal sorting. Context: Sorting data using the strategy (not sure how it'll do it) a,b,c,d,e
Client: Strategy is set to reverse sorting. Context: Sorting data using the strategy (not sure how it'll do it) e,d,c,b,a
/// Defines an injectable strategy for building routes. traitRouteStrategy { fnbuild_route(&self, from: &str, to: &str); }
structWalkingStrategy;
implRouteStrategyforWalkingStrategy { fnbuild_route(&self, from: &str, to: &str) { println!("Walking route from {} to {}: 4 km, 30 min", from, to); } }
structPublicTransportStrategy;
implRouteStrategyforPublicTransportStrategy { fnbuild_route(&self, from: &str, to: &str) { println!( "Public transport route from {} to {}: 3 km, 5 min", from, to ); } }
Walking route from Home to Club: 4 km, 30 min Walking route from Club to Work: 4 km, 30 min Public transport route from Home to Club: 3 km, 5 min Public transport route from Club to Work: 3 km, 5 min
letnavigator = Navigator::new(|from, to| println!("Specific route from {} to {}", from, to)); navigator.route("Home", "Club"); navigator.route("Club", "Work"); }
Output 输出
1 2 3 4 5 6
Walking route from Home to Club: 4 km, 30 min Walking route from Club to Work: 4 km, 30 min Public transport route from Home to Club: 3 km, 5 min Public transport route from Club to Work: 3 km, 5 min Specific route from Home to Club Specific route from Club to Work