Strategy Mode: Strategy (converted from a. Net)

Source: Internet
Author: User
The rule mode is intended for a group Algorithm , Encapsulate each algorithm into an independent class with a common interface, so that they can be replaced with each other. The policy mode allows the algorithm to change without affecting the client.

Suppose we want to design a shopping cart CAT System for e-commerce websites selling books. The simplest case is to multiply the unit price of all goods by the quantity, but the actual situation must be more complicated than that. For example, this website may offer a one-dollar discount for all teaching materials and a 7% discount for comic books, there is a 3% discount for computer books other than teaching materials, and no discount for other books. Because of this complicated discount algorithm, the price calculation problem needs to be systematically solved.

The policy mode can be used to separate the behavior from the environment. The environment class is responsible for maintaining and querying behavior classes, and various algorithms are provided in the specific strategy class (concretestrategy. Because the algorithm and environment are independent, the increase, decrease, and modification of the algorithm will not affect the environment and the client. When a new promotion discount or an existing discount policy changes, you only need to implement a new strategy class and register it on the client. The policy mode is equivalent to "plug-in (Pluggable) algorithms ".

Ii. Structure of policy Mode

Policy mode is the packaging of algorithms. It separates the responsibility for using algorithms from the algorithms themselves and delegates them to different objects for management. Rule mode typically packs a series of algorithms into a series of policy classes and serves as a subclass of an abstract policy class. In one sentence, it is: "prepare a set of algorithms and encapsulate each algorithm so that they can be exchanged. "

Policy is also called the policy mode gof95 ]. The following is a schematic policy pattern structure:


This mode involves three roles:

    • Context Role: Hold a reference to the strategy class.
    • Abstract Policy (Strategy) Role: This is an abstract role, usually implemented by an interface or abstract class. This role provides all the interfaces required for specific policy classes.
    • Concretestrategy: encapsulates related algorithms or actions.

Iii. SchematicSource code

CopySave

 // Strategy pattern -- Structural example  Using System; // "Strategy"  Abstract   Class Strategy { // Methods    Abstract   Public  Void Algorithminterface ();} // "Concretestrategya"  Class Concretestrategya: Strategy { // Methods    Override   Public   Void Algorithminterface () {console. writeline ( "Called concretestrategya. algorithminterface ()" );}} // "Concretestrategyb"  Class Concretestrategyb: Strategy { // Methods    Override   Public   Void Algorithminterface () {console. writeline ( "Called concretestrategyb. algorithminterface ()" );}}// "Concretestrategyc"  Class Concretestrategyc: Strategy { // Methods    Override   Public   Void Algorithminterface () {console. writeline ( "Called concretestrategyc. algorithminterface ()" );}} // "Context"  Class Context { // Fields Strategy strategy; // Constructors    Public Context (strategy Strategy ){ This . Strategy = strategy ;} // Methods    Public   Void Contextinterface () {strategy. algorithminterface ();}} /**/ /// <Summary> /// Client Test  /// </Summary>  Public   Class Client { Public   Static   Void Main ( String [] ARGs ){ // Three contexts following different strategies Context c = New Context ( New Concretestrategya (); C. contextinterface (); Context d = New Context ( New Concretestrategyb (); D. contextinterface (); Context E =New Context ( New Concretestrategyc (); E. contextinterface ();}}

4. When to use specific policy roles

When learning the policy model, students often ask the following question: why can't we see from the policy model which specific policy applies to which situation?

The answer is very simple, and the policy mode is not responsible for this decision. In other words, it is up to the client to decide under what circumstances to use specific policy roles. Policy mode only encapsulates algorithms and provides new algorithms to be inserted into existing systems, and the old algorithms are "retired" from the system. Policy mode does not determine when to use the algorithms.

V. An example of a practical application Policy Model

The following example uses the policy mode to encapsulate different sorting algorithms in sorting objects, so that the client can dynamically Replace the sorting policies (including quicksort, shellsort, and mergesort ).

Copy Save
// Strategy pattern -- real world example  Using System; Using System. collections; // "Strategy"  Abstract   Class Sortstrategy { // Methods    Abstract   Public   Void Sort (arraylist list );} // "Concretestrategy"  Class Quicksort: sortstrategy { // Methods    Public   Override   Void Sort (arraylist list) {list. Sort (); // Default is quicksort Console. writeline ("Quicksorted list" );}} // "Concretestrategy"  Class Shellsort: sortstrategy { // Methods    Public   Override   Void Sort (arraylist list ){ // List. shellsort (); Console. writeline ( "Shellsorted list" );}} // "Concretestrategy"  Class Mergesort: sortstrategy { // Methods    Public   Override   Void Sort (arraylist list ){ // List. mergesort (); Console. writeline ("Mergesorted list" );}} // "Context"  Class Sortedlist { // Fields    Private Arraylist list = New Arraylist (); Private Sortstrategy; // Constructors    Public   Void Setsortstrategy (sortstrategy ){ This . Sortstrategy = sortstrategy ;} // Methods    Public   Void Sort () {sortstrategy. Sort (list );} Public   Void Add (String Name) {list. Add (name );} Public   Void Display (){ Foreach ( String Name In List) console. writeline ( "" + Name );}} /**/ /// <Summary> /// Strategyapp Test  /// </Summary>  Public   Class Strategyapp { Public   Static   Void Main ( String [] ARGs ){ // Two contexts following different strategies Sortedlist studentrecords = New Sortedlist (); studentrecords. Add ( "Samuel" ); Studentrecords. Add ( "Jimmy" ); Studentrecords. Add ( "Sandra" ); Studentrecords. Add ( "Anna" ); Studentrecords. Add ( "Vivek" ); Studentrecords. setsortstrategy ( New Quicksort (); studentrecords. Sort (); studentrecords. Display ();}}

6. Under what circumstances should I use the policy mode?

The policy mode should be considered in the following situations:

1. If there are many classes in a system, the difference between them is only their behavior, then the policy mode can dynamically allow an object to select a behavior among many behaviors.

2. A system must dynamically select one of several algorithms. These algorithms can be encapsulated into specific algorithm classes, which are subclasses of an abstract algorithm class. In other words, these specific algorithm classes have a unified interface. Due to the polymorphism principle, the client can choose to use any specific algorithm class and only hold one data type as the object of the abstract algorithm class.

3. The data used by a system algorithm cannot be known to the client. The policy mode prevents clients from involving complex and algorithm-only data that is not necessary for access.

4. if an object has many behaviors and the appropriate mode is not used, these behaviors must be implemented using multiple conditional selection statements. In this case, the policy mode is used to transfer these actions to the corresponding specific policy class, so that you can avoid using the multi-Condition Selection statements that are difficult to maintain and reflect the concept of object-oriented design.

VII. Advantages and disadvantages of the Policy Model

The rule mode has many advantages and disadvantages. It has the following advantages:

1. The policy mode provides methods for managing related algorithm families. The hierarchical structure of a policy class defines an algorithm or behavior family. If inheritance is used properly, the publicCodeMove to the parent class to avoid repeated code.

2. The rule mode provides a way to replace the inheritance relationship. Inheritance can process multiple algorithms or actions. If the policy mode is not used, the Environment class that uses algorithms or behaviors may have some subclasses. each subclass provides a different algorithm or behavior. However, in this way, the user of an algorithm or behavior is mixed with the algorithm or behavior itself. The logic that determines which algorithm to use or which behavior to take is mixed with the logic of the algorithm or behavior, so that it is impossible to evolve independently. Inheritance makes it impossible to dynamically change algorithms or behaviors.

3. Use Policy mode to avoid using multiple conditional transfer statements. Multiple transfer statements are not easy to maintain. they mix the logic of which algorithm or behavior is adopted with the logic of the algorithm or behavior and are all listed in a multiple transfer statement, it is more primitive and backward than the inheritance method.

Disadvantages of the Policy mode include:

1. The client must know all the policy classes and decide which one to use. This means that the client must understand the differences between these algorithms so that appropriate algorithm classes can be selected in a timely manner. In other words, the policy mode is only applicable when the client knows all the algorithms or actions.

2. The rule mode causes many policy classes. Sometimes you can save the environment-dependent status to the client and design the policy class to be shared so that the policy class instance can be used by different clients. In other words, you can use the metadata mode to reduce the number of objects.

8. Others

The rule mode is widely associated with many other models. Strategy is easily confused with the bridge mode. Although they have similar structures, they are designed to solve different problems. The Strategy Mode focuses on algorithm encapsulation, while the Bridge Mode focuses on separating abstraction and implementation, providing different implementations for an abstract system. Both the bridge and strategy modes reflect the viewpoint of "favor composite over inheritance.

We recommend that you read IOC container and dependency injection mode by Martin Fowler. You can find the Chinese PDF file on the Internet. It provides a very good solution for implementing the policy model.

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.