The strategy model of Java and schema--one of the best policy patterns I've ever seen. Blog post

Source: Internet
Author: User
the strategy model of Java and Schema (reprinted from http://www.cnblogs.com/java-my-life/archive/2012/05/10/2491891.html)

In Dr Shanhong's "Java and Schema" book, this describes the policy (strategy) pattern:

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

The strategy pattern is the wrapper of the algorithm, which separates the responsibility of the algorithm and the algorithm itself, and assigns it to different object management. A policy pattern typically wraps a series of algorithms into a series 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 instance of the policy pattern.

This pattern involves three roles:

Environment (context) role: holds a strategy reference.

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

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

Environment Role Class

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

Abstract Policy class

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

Specific policy classes

Public class Concretestrategya implements strategy {

    @Override public
    void Strategyinterface () {
        // Related Business
    }

}
Public class Concretestrategyb implements strategy {

    @Override public
    void Strategyinterface () {
        // Related Business
    }

}
Public class CONCRETESTRATEGYC implements strategy {

    @Override public
    void Strategyinterface () {
        //related business
    }

}

   Working with scenes

Suppose you now want to design a shopping cart system for E-commerce sites that sell all kinds of books. One of the easiest things to do is to multiply the unit price of all goods, but the actual situation is certainly more complicated than that. For example, this site may provide 20% discount per copy for all senior members, 10% discount for intermediate members and no discount for junior members.

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

Algorithm one: There is no discount for junior members.

Algorithm two: To provide 10% of intermediate members of the promotional discount.

Algorithm three: To provide 20% discount on the promotion of senior members.

The structure diagram that uses the policy pattern to implement is as follows:

Source Code

Abstract Discount Class

Public interface Memberstrategy {
    /**
     * Calculates the price of a book
     * @param booksprice    book's original price
     * @return    Calculate the discounted price/public
    double CalcPrice (double booksprice);

Junior Member Discount Category

public class Primarymemberstrategy implements Memberstrategy {

    @Override public
    double CalcPrice (double Booksprice) {
        
        System.out.println ("No discount for junior members");
        Return Booksprice
    }

}

Intermediate Member Discount Category

public class Intermediatememberstrategy implements Memberstrategy {

    @Override public
    double CalcPrice (double Booksprice) {

        System.out.println ("Discount for intermediate members is 10%");
        return booksprice * 0.9;
    }

Premium Member Discount Category

public class Advancedmemberstrategy implements Memberstrategy {

    @Override public
    double CalcPrice (double Booksprice) {
        
        System.out.println ("Discount for Premium Members is 20%");
        return booksprice * 0.8;
    }

Price category

public class Price {
    //holds a specific policy object
    private memberstrategy strategy;
    /**
     * constructor, passing in a specific policy object
     * @param strategy    specific policy object/public
     price
    (Memberstrategy strategy) {
        This.strategy = strategy;
    }
    
    /**
     * Calculate the price of a book *
     @param the original value of the Booksprice    book
     * @return    calculate the price after the discount
    /public double QUOTE (double booksprice) {return
        this.strategy.calcPrice (booksprice);
    }
}

Client

public class Client {public

    static void Main (string[] args) {
        //Select and create the policy object you want to use
        memberstrategy strategy = New Advancedmemberstrategy ();
        Create environment price Price
        = new Price (strategy);
        Calculated price
        Double quote = Price.quote (+);
        System.out.println ("The final price of the book is:" + quote);
    }

As can be seen from the example above, the policy pattern simply encapsulates the algorithm, provides new algorithms to insert into the existing system, and the old algorithm "retires" from the system, and the policy pattern does not determine when and when to use the algorithm. Under what circumstances the algorithm is determined by the client. Cognitive Strategy Model

  the focus of the strategy model

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

  the equality of Algorithms

A great feature of the strategy pattern is the equality of each strategy algorithm. For a series of specific strategy algorithms, everyone's position is exactly the same, precisely because of this equality, can realize the algorithm between each other to replace. All strategy algorithms are independent of each other in implementation and are not dependent on each other.

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

  uniqueness of the Run-time policy

  During the run, the policy pattern can only use one specific policy implementation object at a time, although it can be dynamically switched in different policy implementations, but only one at a time.

  the act of being public

  It is often seen that all the specific policy classes have some public behavior. At this time, we should put these public behavior into the common abstract strategy role strategy class. Of course this time the abstract policy role must be implemented with Java abstract classes, not interfaces.

This is also a typical standard practice for centralizing code above the hierarchy of inheritance.

Advantages of 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.