Java and design patterns-Rule patterns

Source: Internet
Author: User

Java and design patterns-Rule patterns

In actual development, you may encounter a situation where the implementation of a function is divided into multiple algorithms that can be considered as a policy, select different algorithms or policies for the actual operation to get the final result. In real life, these examples are also not to mention, for example, the mall held activities, full 100 yuan minus 10 yuan, full 200 yuan minus 30 yuan, full 500 yuan minus 100 yuan and so on... in this way, based on the amount of money consumed, the final amount of money to be paid corresponds to different algorithms, and different calculation methods can be considered as different strategies. When shopping in a certain East Region, discounts vary according to different user levels.

For the UML class diagram of the Rule mode, refer:

If there is no policy model, how can we achieve the final payment of a certain Eastern Shopping calculation?

Package com. strategy. demo; public class NoStrategy {/*** do not use the Measurement Mode * @ param args */private static final int NOCARDUSER = 1; private static final int IRONCARDUSER = 2; private static final int GOLDCARDUSER = 3; public static void main (String [] args) {NoStrategy NoStrategy1 = new NoStrategy (); NoStrategy NoStrategy2 = new NoStrategy (); noStrategy NoStrategy3 = new NoStrategy (); System. out. println ("the final payable of buyers who have no cards to buy 100 yuan of goods:" + NoStrategy1.getPrice (100.0, 1); System. out. println ("the final payable for purchasing 100 yuan worth of goods by iron brand buyers:" + NoStrategy2.getPrice (100.0, 2); System. out. println ("the final payable for a gold buyer who buys 100 yuan of goods:" + 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 instance:

Ah, I got the correct answer. Should you be satisfied now? Should you rest assured? Suddenly, the supervisor said that the category of diamond users should be increased, and the diamond users should be given a discount. How can you achieve this? Adding the diamond user type, adding the method for calculating diamond users, and then adding the I f else? In this way, functions can be implemented, but does it not meet the principle of opening/closing? As the number of users increases, does your if else become longer and more complex? Which leads to increasingly poor system scalability and stability? Therefore, this method is obviously not feasible in practice. Let's take a look at how to use the policy mode to meet the above requirements.

1. PriceStrategyInterface interface, which corresponds to the Strategy interface in the UML class diagram:

package com.strategy.demo;public interface PriceStrategyInterface {double calPrice(double price);}


2. Implementation class, non-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 brand buyer * (non-Javadoc) * @ see com. strategy. demo. priceStrategyInterface # calPrice (double) */@ Overridepublic double calPrice (double price) {return price * 0.9 ;}}


4. Implementation class. Gold Card Users:

Package com. strategy. demo; public class GoldCardUserStrategy implements PriceStrategyInterface {/*** gold buyer */@ Overridepublic double calPrice (double price) {return price * 0.7 ;}}


5. Environment object used to operate the policy:

Package com. strategy. demo; public class PriceContext {/*** operation class */PriceStrategyInterface priceStrategyInterface;/** input object through initialization */public PriceContext (PriceStrategyInterface priceStrategyInterface) {this. priceStrategyInterface = priceStrategyInterface;}/** return value through object calculation */public double getPrice (double price) {return priceStrategyInterface. calPrice (price );}}

When the environment object is initialized, the corresponding policy object is passed in, and then the calculation value is returned by calling the method.

6. Build a test class and test:

Package com. strategy. demo; public class TestClass {public static void main (String [] args) {PriceContext priceContext = new PriceContext (new NoCardUserStrategy (); System. out. println ("the final payable of buyers who have no cards to buy 100 yuan of goods:" + priceContext. getPrice (100.0); PriceContext priceContext2 = new PriceContext (new IronCardUserStrategy (); System. out. println ("final payable for purchasing 100 yuan of goods by iron brand buyers:" + priceContext2.getPrice (100.0); PriceContext priceContext3 = new PriceContext (new GoldCardUserStrategy (); System. out. println ("the final payable for a gold buyer who bought 100 yuan of goods:" + priceContext3.getPrice (100.0 ));}}

Run the above instance:

I got the correct answer in the same way as the first method. How can we achieve this if we want to increase the category of a diamond buyer? 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 the test class adds a diamond buyer's shopping:

Package com. strategy. demo; public class TestClass {public static void main (String [] args) {PriceContext priceContext = new PriceContext (new NoCardUserStrategy (); System. out. println ("the final payable of buyers who have no cards to buy 100 yuan of goods:" + priceContext. getPrice (100.0); PriceContext priceContext2 = new PriceContext (new IronCardUserStrategy (); System. out. println ("final payable for purchasing 100 yuan of goods by iron brand buyers:" + priceContext2.getPrice (100.0); PriceContext priceContext3 = new PriceContext (new GoldCardUserStrategy (); System. out. println ("the final payable for a gold buyer's 100 yuan purchase:" + priceContext3.getPrice (100.0); PriceContext priceContext4 = new PriceContext (new DiamondUserStrategy (); System. out. println ("the final payment for the 100 yuan goods purchased by the diamond card buyer:" + priceContext4.getPrice (100.0 ));}}

Running instance:



Is it very easy to expand? The organization is also very clear. Summarize the advantages of the Policy mode:

1. Clear structure, simple and intuitive to use;

2. Reduced system coupling and convenient scalability;

3. Complete operation encapsulation and data security. (In TestClass, we only know the implementation class and do not involve specific calculation methods)

Of course, policy methods also have some disadvantages:

As shown in the figure, the number of sub-classes increases with the increasing number of policies.

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.