Design Pattern series-strategy Pattern

Source: Internet
Author: User
ArticleDirectory
    • Strategy Pattern
Strategy patternfrom Wikipedia, the free encyclopedia

Jump to: navigation, search

In computer programming,Strategy PatternIs a particle software design pattern, whereby algorithms can be selected at runtime.

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.

This pattern is invisible in different ages with first-class functions. 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
    • 1 digoal
    • 2 code examples
      • Java 2.1
      • Python 2.2
      • 2.3 C #
      • 2.4 ActionScript 3
    • 3 Strategy versus Bridge
    • 4 strategy pattern and OCP
    • 5 See also
    • 6 external links

Digoal

Code examples

Java
Package Wikipedia. patterns. strategy; // mainapp test applicationclass mainapp {public static void main (string [] ARGs) {context; // three contexts following different strategies context = new context (New concretestrategya (); context.exe cute (); Context = new context (New concretestrategyb (); context.exe cute (); context = new context (New concretestrategyc (); context.exe cute ();}} // The classes that implement a concrete strategy shocould 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.exe cute ()") ;}} class concretestrategyb implements istrategy {public void execute () {system. out. println ("called concretestrategyb.exe cute ()") ;}} class concretestrategyc implements istrategy {public void execute () {system. out. println ("called concretestrategyc.exe cute ()") ;}// 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.exe cute ();}}

Python

Python has first-class functions, so there's no need to implement this pattern explicitly. 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 strategiesbutton1 = button (sum, "add 'em") button2 = button (lambda Nums :"". join (MAP (STR, Nums), "Join 'em") # test each buttonnumbers = 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"

C #
 Using System; Namespace Wikipedia. patterns. Strategy {// Mainapp test application    Class Mainapp { Static   Void Main () {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 shold 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 ();}}}

ActionScript 3
// Invoked from application. initializeprivate function Init (): void {var context: context; Context = new context (New concretestrategya (); context.exe cute (); Context = new context (New concretestrategyb ()); context.exe cute (); Context = new context (New concretestrategyc (); context.exe cute ();} 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.exe cute (); invoked") ;}} package Org. wikipedia. patterns. strategy {public final class concretestrategyb implements istrategy {public function execute (): void {trace ("concretestrategyb.exe cute (); invoked") ;}} package Org. wikipedia. patterns. strategy {public final class concretestrategyc implements istrategy {public function execute (): void {trace ("concretestrategyc.exe cute (); 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.exe cute ();}}}

Strategy versus Bridge

The UML class digoal for the strategy pattern is the same as the digoal for the Bridge pattern. However, these two design patterns aren't the same in theirIntent. While the Strategy pattern is meantBehavior, The Bridge pattern is meantStructure.

The coupling between the context and the strategies is tighter than the coupling between the specified action and the implementation in the bridge pattern.

Strategy pattern and OCP

According to strategy pattern, the behaviors of A Class shocould not be inherited, instead they shoshould 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 into SS 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 abstract 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:

Brakebehavior = new brake ();

This gives greater flexibility in design and is in harmony with OCP (open closed principle) That States Classes shocould be open for extension but closed for modification.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.