Design mode strategy (strategy) mode

Source: Internet
Author: User

The strategy mode is a behavioral design pattern that encapsulates the algorithm one at a time and can use one of the algorithms interchangeably at some point. Conceptually, all of these algorithms are doing the same thing, just realizing the difference.

Motivation

In development, we often encounter tasks that are conceptually the same, dealing with different methods, for example, using different tax calculation methods for a product to calculate its price. In general, there are the following methods to handle:

    • Copy and paste (one copy of the code with two versions, large maintenance costs)
    • Use a switch or if statement to specify various situations with a variable (the branch grows longer)
    • function pointer or delegate (unable to maintain the state of the object)
    • Inheritance (Customer code still has to change when demand changes)

The strategy mode solves the problem by using the following methods:

    1. Look for changes, such as the existing change algorithms here, to encapsulate them in a separate class
    2. Include this class in another class, that is, use a combination to replace the inheritance
Defined

Define a series of algorithms, encapsulate them one by one, and use them to replace each other, and the strategy pattern allows the algorithm to change independently of the customers who use it.

Effect

By deriving a different algorithm from an abstract class, the customer does not have to care about which algorithm is actually used, which makes it convenient to add the new algorithm.

Structure

Strategy

The interface of the algorithm is defined, and the context class uses this interface to invoke the specific algorithm. Strategy can be an abstract class (C + +), or an interface (Java)

Concretestrategy

Implementing a specific algorithm

Context

Contains a reference to a strategy object, and it does not care whether the strategy object is Concretestrategya or CONCRETESTRATEGYB, strategy by Algorithminterface () interface to correctly invoke the specific algorithm.

Client

Customers, interacting with Contex. Typically, the client creates a concretestartegy and passes it to the context and sends a processing request to Contex.

Example 1. Define Interface Strategy

Strategy.java

publicinterface Strategy {   publicintdoOperation(intint num2);}
2. Define the specific algorithm Concretestrategy

Operationadd.java

publicclass OperationAdd implements Strategy{   @Override   publicintdoOperation(intint num2) {      return num1 + num2;   }}

Operationsubstract.java

publicclass OperationSubstract implements Strategy{   @Override   publicintdoOperation(intint num2) {      return num1 - num2;   }}

Operationmultiply.java

publicclass OperationMultiply implements Strategy{   @Override   publicintdoOperation(intint num2) {      return num1 * num2;   }}
3. Create a Context class

Context.java

publicclass Context {   private Strategy strategy;   publicContext(Strategy strategy){      this.strategy = strategy;   }   publicintexecuteStrategy(intint num2){      return strategy.doOperation(num1, num2);   }}
4. Customer (client) uses the context class

Strategypatterndemo.java

 Public classStrategypatterndemo { Public Static void Main(string[] args) {Context context =NewContext (NewOperationadd ()); System. out. println ("Ten + 5 ="+ Context.executestrategy (Ten,5)); Context =NewContext (NewOperationsubstract ()); System. out. println ("10-5 ="+ Context.executestrategy (Ten,5)); Context =NewContext (NewOperationmultiply ()); System. out. println ("Ten * 5 ="+ Context.executestrategy (Ten,5)); }}
5. Output

10 + 5 = 15
10-5 = 5
10 * 5 = 50

Resources
    1. Https://en.wikipedia.org/wiki/Strategy_pattern
    2. Http://www.oodesign.com/strategy-pattern.html
    3. Http://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
    4. "Design Pattern Analysis (second edition)"
    5. Http://www.javacodegeeks.com/2013/08/strategy-design-pattern-in-java-example-tutorial.html

Copyright NOTICE: This article is the original blogger article, reproduced please indicate the source: http://blog.csdn.net/lihao21

Design mode strategy (strategy) mode

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.