Design pattern in a comprehensible way--strategy mode (strategy pattern)

Source: Internet
Author: User

Mode motive

There are many different ways to accomplish a task, each of which is called a strategy, and we can choose different strategies to accomplish this task depending on the environment or the conditions.
In software development also often encounter similar situation, to achieve a certain function has a number of ways, at this time can use a design mode to make the system can choose the solution flexibly, but also can easily add new solutions.

In software systems, there are many algorithms that can implement a function, such as finding, sorting, and so on, a common method is hard-coded (Coding) in a class, if you need to provide a variety of search algorithms, you can write these algorithms into a class, in the class to provide multiple methods, Each method corresponds to a specific search algorithm; Of course, these algorithms can be encapsulated in a unified approach, through the if...else ... and other conditional judgment statements to make the selection. Both of these implementations can be called hard-coded, and if a new lookup algorithm needs to be added, the source code of the encapsulated algorithm class needs to be modified, and the client calling code needs to be changed. In this algorithm class to encapsulate a large number of search algorithms, the class code will be more complex, maintenance is more difficult.

In addition to providing a specialized search algorithm class, you can also include the algorithm code directly in the client program, which makes the client program large and difficult to maintain, and the problem becomes more serious if there are a large number of algorithms to choose from.
In order to solve these problems, we can define some independent classes to encapsulate different algorithms, each of which encapsulates a specific algorithm, where each class of encapsulation algorithm can be called a strategy (strategy), in order to guarantee the consistency of these policies, we usually use an abstract policy class to define the algorithm. Each of these algorithms corresponds to a specific policy class.

Pattern definition
Policy mode (strategy pattern): Defines a series of algorithms that encapsulate each algorithm and allow them to be replaced by each other. The policy pattern makes the algorithm independent of the customer using it, also known as the policy mode. The policy mode is an object-based behavior pattern.
Strategy Pattern:define A family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients.
Frequency of Use:medium High
UML diagram

Pattern structure
The policy pattern contains the following roles:
Context: Environment class
Strategy: Abstract Policy class
Concretestrategy: Specific policy classes

Pattern Analysis
The strategy pattern is a relatively easy to understand and use the design pattern, the strategy pattern is the encapsulation of the algorithm, it divides the responsibility of the algorithm and the algorithm itself, delegating to different object management. The strategy pattern typically encapsulates a series of algorithms into a set of policy classes as subclasses of an abstract policy class. In a word, it is "preparing a set of algorithms and encapsulating each algorithm so that they can be interchanged".

In policy mode, it is up to the client to decide under what circumstances the specific policy role should be used.
The strategy pattern only encapsulates the algorithm, provides a new algorithm to insert into the existing system, and the old algorithm "retired" from the system convenient, the strategy mode does not decide when to use which algorithm, the choice of the algorithm is determined by the client. This improves the flexibility of the system to a certain extent, but the client needs to understand the differences between all the specific policy classes in order to choose the appropriate algorithm, which is one of the drawbacks of the strategy model, which in some way increases the difficulty of using the client.

Pattern Instances and parsing
Mall Promotions-Strategy mode sample code
System structure

Context: Environment class CashContext.cs

namespacestrategypattern{classCashcontext {PrivateCashsuper CS; //through the construction method, the specific charge policy is introduced         PublicCashcontext (stringtype) {            Switch(type) { Case "Normal Charges": Cashnormal cs0=NewCashnormal (); CS=Cs0;  Break;  Case "Full 300 return": Cashreturn cs1=NewCashreturn (" -"," -"); CS=CS1;  Break;  Case "Call 80 percent": Cashrebate CS2=NewCashrebate ("0.8"); CS=CS2;  Break; }        }         Public DoubleGetResult (DoubleMoney ) {            //Obtain the results of the calculation according to the different charging strategy            returnCs.acceptcash (Money); }    }}

Strategy: Abstract Policy class CashSuper.cs

namespace strategypattern{    // Cash charges abstract class      cashsuper    {        publicabstractdouble acceptcash (double  ) ;    }}

Concretestrategy: Specific strategy class CashNormal.cs

namespace strategypattern{    // normal charge subclass class      cashnormal:cashsuper    {         publicoverridedouble acceptcash (double Money )        {             return money ;     }}}

CashRebate.cs

namespacestrategypattern{//Discounted charges sub-category    classCashrebate:cashsuper {Private DoubleMoneyrebate =1d;  PublicCashrebate (stringmoneyrebate) {             This. moneyrebate =Double.        Parse (moneyrebate); }         Public Override DoubleAcceptcash (DoubleMoney ) {            returnMoney *moneyrebate; }    }}

CashReturn.cs

usingSystem;namespacestrategypattern{//Rebate Fees sub-category    classCashreturn:cashsuper {Private DoubleMoneycondition =0.0d; Private DoubleMoneyreturn =0.0d;  PublicCashreturn (stringMoneycondition,stringMoneyreturn) {             This. moneycondition =Double.            Parse (moneycondition);  This. Moneyreturn =Double.        Parse (Moneyreturn); }         Public Override DoubleAcceptcash (DoubleMoney ) {            Doubleresult =Money ; if(Money >=moneycondition) Result= Money-math.floor (money/moneycondition) *Moneyreturn; returnresult; }    }}

Client: Customer Class

usingSystem;usingSystem.Windows.Forms;namespacestrategypattern{ Public Partial classForm1:form {//declares a double variable total to calculate totals        DoubleTotal =0.0d;  PublicForm1 () {InitializeComponent (); }        Private voidBtnok_click (Objectsender, EventArgs e) {Cashcontext cc=NewCashcontext (cbxType.SelectedItem.ToString ()); DoubleTotalprices =0d;; Totalprices= CC. GetResult (convert.todouble (txtprice.text) *convert.todouble (Txtnum.text)); //count each item in totalTotal = Total +totalprices; LBXLIST.ITEMS.ADD ("Unit Price:"+ Txtprice.text +"Quantity:"+ Txtnum.text +"Total:"+totalprices.tostring ()); Lblresult.text=Total .        ToString (); }        Private voidForm1_Load (Objectsender, EventArgs e) {CbxType.Items.AddRange (New Object[] {"Normal Charges","Full 300 return","Call 80 percent" }); Cbxtype.selectedindex=0; }    }}

Model Pros and cons
Advantages of the policy model
The policy model provides perfect support for the "open and close" principle, which allows users to choose an algorithm or behavior without modifying the original system, or to add new algorithms or behaviors flexibly.
The policy model provides a way to manage the associated algorithm families.
The policy model provides a way to replace an inheritance relationship.
? Use policy mode to avoid using multiple conditional transfer statements.

Disadvantages of the policy model
? The client must know all the policy classes and decide for itself which policy class to use.
The policy pattern will result in many policy classes that can reduce the number of objects to some extent by using the enjoy meta mode.

Mode applicable environment
You can use the policy mode in the following situations:
? If there are many classes in a system, the difference between them is only their behavior, then the use of policy mode can dynamically let an object in many behaviors to choose a behavior.
? A system needs to dynamically select one of several algorithms.
? If an object has a lot of behavior, if the appropriate pattern is not used, the behavior has to be implemented using multiple conditional selection statements.
? Do not want the client to know the complex, algorithm-related data structure, in the specific policy class to encapsulate the algorithm and related data structure, improve the confidentiality and security of the algorithm.

"Statement and thanks"
This article, on the shoulders of many giants, draws on and cites many other works or writings that others have copyrighted, and is here to thank the former people for their contributions. And at the same time publish the quoted content, the original author or source (some of the content from the Internet can not be traced to the source, deeply regret).

"References"
Design mode-the basis of reusable object-oriented software author: [US] Erich gamma/richard Helm/ralph johnson/john vlissides Translator: Li Yingjun/Ma Xiaoxing/Cai Min/Liu Jianzhong and other machinery industry press
Refactoring-Improving the design of existing code author: Martin Fowler Translator: China Power Press, HOU-jie
"Agile software Development-principles, patterns and practices" Author: Robert C. Martin Tsinghua University Press
"Programmer's path to cultivation-from small to expert" by Andrew hunt/david Thomas Electronics Press
Head First design mode author: Freeman translator: O ' Reilly Taiwan company China Power Press
"Zen of Design Pattern" Author: Qin Xiaobo Machinery Industry Press
MSDN Webcast "C # Object-oriented design mode discussion on" lecturer: Li Jianzhong
Liu wei. design mode. Beijing: Tsinghua University Press, 2011.
Liu wei. Design pattern Training Tutorial. Beijing: Tsinghua University Press, 2012.
"Big Liar design Mode" Author: Geoscience Tsinghua University Press
C # Illustrated Tutorial Author: Solis Translator: Surin/Zhu Ye People's post and telecommunications press
"You must know. NET" Author: Wang Tao
. NET in Project author: Li Tianping Electronics Press
The Microsoft. NET Enterprise Application Architecture Design Author: (US) Esposito and other translators: Chen Lifu
http://www.dofactory.com/Patterns/Patterns.aspx. NET Design Patterns
Http://www.cnblogs.com/zhenyulu Blog Lu Zhenyu
Http://www.cnblogs.com/terrylee Blog Li Huijun
http://www.cnblogs.com/anlyren/Blog Anlyren
Http://www.cnblogs.com/idior Blog Idior
Http://www.cnblogs.com/allenlooplee blog Allen Lee
HTTP://BLOG.CSDN.NET/AI92 Blog ai92
http://www.cnblogs.com/umlonline/Blog Zhang
http://www.cnblogs.com/lovecherry/Blog Lovecherry

Design pattern in a comprehensible way--strategy mode (strategy pattern)

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.