Policy mode (strategy method)

Source: Internet
Author: User

The policy pattern can be considered as "pluggable algorithm (pluggable)", separating the behavior of subclasses from the common logic, and abstracting the behavior of subclasses into common logic, so that the behavior of substituting subclasses does not affect the public logic, nor does it affect the logic of the calling class.

  

The following is a simple example of a strategy pattern, as shown in the following class diagram:

The code for the public logic context is as follows:

 Public classcontext{ Public voidContextinterface () {//Add common code hereStrategy.strategyinterface (); //Add common code here    }    /**     * @linkAggregation * @directed*/    Privatestrategy strategy; Private voidSetstrategy (Strategy strategy) { This. Strategy =strategy; }    PrivateStrategy Getstrategy () {return  This. Strategy; }}

The interface of the sub-class algorithm is as follows:

Abstract  Public class strategy{    publicabstractvoid  strategyinterface ();}

The specific algorithm is as follows:

 Public class extends strategy{    publicvoid  strategyinterface () {        //write you Algorithm codehere    }}

When we want to modify the implementation of the specific algorithm, we just rewrite a class, inherit the strategy interface, the public logic in the context does not need to be modified.

Examples of policy patterns in Java:

The environment role is played by container, the algorithm interface is played by LayoutManager, and the concrete algorithm is played by GridBagLayout, GridLayout and so on.

Policy mode (strategy method)

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.