Design mode 21-strategy Policy mode

Source: Internet
Author: User
Tags abstract inheritance


From


The policy mode belongs to the behavior pattern of the object. It is intended for a set of algorithms that encapsulate each algorithm in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client.

The strategy pattern is the wrapper over the algorithm, which separates the responsibility of the algorithm and the algorithm itself, delegating to different object management. The strategy pattern typically wraps a series of algorithms into a set of policy classes as subclasses of an abstract policy class. In a word, it is: "Prepare a set of algorithms and encapsulate each algorithm so that they can be interchanged." The following is a schematic implementation of the structure of the policy pattern instance.

This pattern involves three characters:

Environment (context) role: holds a reference to a strategy.

abstract Policy (strategy) role: This is an abstract role, usually implemented by an interface or abstract class. This role gives the interfaces required for all the specific policy classes.

specific policy (concretestrategy) Role: wraps the associated algorithm or behavior.

code example:

Environment Role Class:

public class Context {
    //The object that holds a specific policy
    private strategy strategy;
    /**
     * constructor, passing in a specific policy object
     * @param strategy    specific policy Object
     *
    /public Context (strategy strategy) {
        This.strategy = strategy;
    }
    /**
     * Policy methods */public
    void Contextinterface () {
        strategy.strategyinterface ();
    }
    
}

Abstract policy Classes

Public interface Strategy {
    /**
     * Policy Method
     *
    /public void Strategyinterface ();

Specific Strategy Class 1

Public class Concretestrategya implements strategy {
    @Override public
    void Strategyinterface () {
        // Related Business
    }
}

Specific Strategy Class 2

Public class Concretestrategyb implements strategy {
    @Override public
    void Strategyinterface () {
        //related business
    }
}

Usage Scenarios

Suppose now to design a shopping cart system for e-commerce sites that sell all kinds of books. One of the simplest cases is to multiply the unit price of all goods, but the reality is definitely more complicated than this. For example, this website may offer 20% discount per copy for all Premium members, 10% discount per copy for intermediate members and no discount for junior members.

According to the description, the discount is based on one of several algorithms in the following:

Algorithm one: There is no discount for junior members.

Algorithm two: To provide 10% discount for intermediate members.

Algorithm three: Offer 20% discount for Premium members.

The structure diagram implemented using the policy mode is as follows:

source code Abstract Discount Class

Public interface Memberstrategy {
    double calcprice (double booksprice);                                                                      
}

Junior Member Discount Category

public class Primarymemberstrategy implements Memberstrategy {public
    double CalcPrice (double booksprice) {
        System.out.println ("No Discount for Primary");
        return booksprice;                                                                                    
    }
}

Intermediate Member Discount Category

public class Intermediatememberstrategy implements Memberstrategy {public
    double CalcPrice (double booksprice) {
        System.out.println ("10% Discount for Intermediate");
        Return Booksprice *. 9;                                                                               
    }
}

Premium Membership Discount Category

public class Advancedmemberstrategy implements Memberstrategy {public
    double CalcPrice (double booksprice) {
        System.out.println ("20% for advanced members.");
        Return booksprice *. 8;                                                                               
    }
}

Price category

public class Price {
    private memberstrategy member;

    Public Price (Memberstrategy member) {
        this.member = member;
    }
    Public double quote (double booksprice) {
        return member.calcprice (Booksprice);                                                                  
    }
}

Test

public class Client {public
    static void Main (string[] args) {
        memberstrategy member = new Advancedmemberstrategy ( );
        Price Price = new Price (member);
        Double quote = Price.quote (+);
        System.out.println ("The Total Price is:" + quote);                                                   
    }
}

As can be seen from the above example, the policy pattern only encapsulates the algorithm, provides a new algorithm to insert into the existing system, and the old algorithm "retired" from the system, the strategy mode does not determine when to use which algorithm. The client determines under what circumstances the algorithm is used. recognize strategy patterns

  the focus of the strategy model

The focus of the strategy pattern is not how to implement the algorithm, but how to organize, call these algorithms, so that the program structure more flexible, with better maintainability and extensibility.

  equality of the algorithm

A big feature of the strategy model is the equality of each strategy algorithm. For a series of specific strategy algorithms, everyone's status is exactly the same, because of this equality, can be achieved between the algorithm to replace each other. All strategy algorithms are independent of each other in implementation, and are not dependent on each other.

So you can describe this series of strategy algorithms: Policy algorithms are different implementations of the same behavior.

  uniqueness of the run-time policy

   during operation, the policy mode can only use one specific policy implementation object at a time, although it is possible to dynamically switch between different policy implementations, but only one can be used at a time.

  the act of the public

   It is common to see that all specific policy classes have some public behavior. At this time, the public behavior should be put into the common abstract strategy role strategy class inside. Of course, abstract policy roles must be implemented in Java abstract classes, not interfaces.

This is also a typical standard practice of centralizing the code to inherit hierarchy.

Advantages of the policy model

(1) The Strategy mode provides a way to manage the associated algorithm families. The hierarchy structure of a policy class defines an algorithm or a family of behaviors. Proper use of inheritance can move common code into the parent class, thus avoiding code duplication.

(2) Use the policy mode to avoid using multiple conditional (IF-ELSE) statements. Multiple conditional statements are difficult to maintain, and it mixes the logic of which algorithm or behavior is taken with the logic of the algorithm or the action, all listed in a multi-conditional statement, more primitive and backward than the method of using inheritance. Disadvantages of the policy model

(1) The client must know all of the policy classes and decide for itself which policy class to use. This means that the client must understand the differences between these algorithms in order to select the appropriate algorithm classes at the right time. In other words, the policy pattern applies only to situations where the client knows the algorithm or behavior.

(2) Since the policy model encapsulates each specific policy implementation as a class, the number of objects can be significant if there are many alternative strategies.





Related Article

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.