Java and Design Patterns-policy mode

Source: Internet
Author: User

In the actual development, may encounter such a situation, the implementation of a certain function is divided into several algorithms, these algorithms can be identified as a strategy, in the actual operation of the choice of different algorithms or strategies to operate to obtain the final result. In real life, these examples are also endless, for example, the shopping malls held activities, a full $100 minus $10, a full $200 minus $30, a full 500 yuan minus 100 yuan and so on ... In this way, each consumption of a sum, according to the amount of money consumed, the calculation of the final payment of the money corresponding to different algorithms, these corresponding different calculation methods can be identified as a different strategy. In some east shopping, according to different user levels, the discount intensity is also different.

UML class diagram references for policy mode:

If there is no strategy mode, how to achieve the final payment method of East shopping?

Package Com.strategy.demo;public class Nostrategy {/** * does not use measurement mode for * @param args */private static final int nocarduser=1;p rivate static final int ironcarduser=2;private static final int goldcarduser=3;public static void main (string[] args) {NoS Trategy nostrategy1=new nostrategy (); Nostrategy nostrategy2=new nostrategy (); Nostrategy nostrategy3=new nostrategy (); System.out.println ("No card buyers buy 100 yuan of goods ultimately payable:" +nostrategy1.getprice (100.0, 1)); System.out.println ("The buyer of the Iron card buys 100 yuan of goods final payment:" +nostrategy2.getprice (100.0, 2)); System.out.println ("Gold buyer buys 100 yuan of goods ultimately payable:" +nostrategy3.getprice (100.0, 3));} Private double Getnocardprice (double price) {return price;} Private double Getironcardprice (double price) {return price*0.9;} Private double Getgoldcardprice (double price) {return price*0.7;} Private double GetPrice (double price,int type) {if (Type==nocarduser) {return getnocardprice (price);} else if (type ==ironcarduser) {return getironcardprice (price);} else if (type ==goldcarduser) {return getgoldcardprice (price);} Else {return 0;}}} 


Running an instance:

Ah, come to the right answer, when you should be satisfied with it, should rest easy? Suddenly, the director said to increase the category of diamond users, diamond users call 60 percent, then how do you achieve it?  Increase the type of diamond users in the inside, and then increase the method of calculating the diamond users, and then add I f else in the final judgment? This can do the function, but is not satisfied with the opening and shutting principle? And with the increasing number of users, is your if else getting longer and more complex? Cause system scalability and stability getting worse? So, this approach is obviously not desirable in practice, let's look at how to use the strategy model to achieve the above requirements.

The 1.PriceStrategyInterface interface corresponds to the strategy interface in the UML class diagram:

Package Com.strategy.demo;public interface Pricestrategyinterface {double calprice (double price);}


2. Implementation class, no card users:

Package Com.strategy.demo;public class Nocarduserstrategy implements Pricestrategyinterface {/** * unlicensed buyer, original price */@ Overridepublic double Calprice (double price) {return price;}}


3. Implementation class, Iron card users:

Package Com.strategy.demo;public class Ironcarduserstrategy implements Pricestrategyinterface {/* * Iron Buyer * (Non-javadoc) * @see Com.strategy.demo.pricestrategyinterface#calprice (double) */@Overridepublic double calprice (double price) { return price*0.9;}}


4. Implementation class, Gold users:

Package Com.strategy.demo;public class Goldcarduserstrategy implements Pricestrategyinterface {/** * Gold buyer */@ Overridepublic double Calprice (double price) {return price*0.7;}}


5. Environment objects, which are used to manipulate policies:

Package Com.strategy.demo;public class Pricecontext {/** * Operation class */pricestrategyinterface pricestrategyinterface;/* * By initializing the Incoming object */public pricecontext (Pricestrategyinterface pricestrategyinterface) {this.pricestrategyinterface= Pricestrategyinterface;} /* * Return value computed by object */public double GetPrice (double price) {return Pricestrategyinterface.calprice (price);}}

When the environment object is initialized, the corresponding policy object is passed in and the method is called to return the computed value.

6. Build the test class and test:

Package Com.strategy.demo;public class TestClass {public static void main (string[] args) {Pricecontext pricecontext=new P Ricecontext (New Nocarduserstrategy ()); System.out.println ("No card buyers buy 100 yuan of goods ultimately payable:" +pricecontext.getprice (100.0)); Pricecontext pricecontext2=new Pricecontext (New Ironcarduserstrategy ()); System.out.println ("The buyer of the Iron card buys 100 yuan of goods final payment:" +pricecontext2.getprice (100.0)); Pricecontext pricecontext3=new Pricecontext (New Goldcarduserstrategy ()); System.out.println ("Gold buyer buys 100 yuan of goods ultimately payable:" +pricecontext3.getprice (100.0));}}

Run the above instance:

Given the same correct answer as the first method, how do we do this if we want to add a diamond buyer's kind? We only need to add a policy implementation class:

Package Com.strategy.demo;public class Diamonduserstrategy implements Pricestrategyinterface {@Overridepublic double Calprice (double price) {return price*0.6;}}


Then test the class to add a diamond buyer to the shopping:

Package Com.strategy.demo;public class TestClass {public static void main (string[] args) {Pricecontext pricecontext=new P Ricecontext (New Nocarduserstrategy ()); System.out.println ("No card buyers buy 100 yuan of goods ultimately payable:" +pricecontext.getprice (100.0)); Pricecontext pricecontext2=new Pricecontext (New Ironcarduserstrategy ()); System.out.println ("The buyer of the Iron card buys 100 yuan of goods final payment:" +pricecontext2.getprice (100.0)); Pricecontext pricecontext3=new Pricecontext (New Goldcarduserstrategy ()); SYSTEM.OUT.PRINTLN ("Gold Buyers buy 100 yuan of goods ultimately payable:" +pricecontext3.getprice (100.0)); Pricecontext pricecontext4=new Pricecontext (New Diamonduserstrategy ()); System.out.println ("Diamond card buyer buys $100 for the final payment of the goods:" +pricecontext4.getprice (100.0));}}


Running an instance:



Is it particularly easy to expand? The organization is also very clear. Summarize the advantages of the strategy model:

1. Clear structure, simple and intuitive to use;

2. The system coupling is reduced, the expansion is convenient;

3. The operation package is complete and the data is more secure. ( in TestClass, only relevant implementation classes are known, and no specific calculation method is involved)

Of course, there are some drawbacks to the strategy approach:

It can be seen intuitively that as the strategy grows, the number of subclasses becomes large.

My favorite friends pay attention to me and my platform

Java and Design Patterns-policy mode

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.