Algorithm encapsulation and switching-policy mode (1)

Source: Internet
Author: User

As the saying goes: All the roads go to Rome. In many cases, there are more than one way to achieve a certain goal. For example, when traveling, we can choose a variety of different travel modes, such as cycling, taking a car, taking a train or taking a plane, select the most suitable travel mode based on the actual situation (destination, travel budget, travel time, etc. When preparing a travel plan, if the destination is far away and there is not much time, but there is no money, you can choose to fly to travel; if the destination is far away but has a long vacation and the travel cost needs to be controlled, you can choose to take a train or a car. If you are healthy and environmentally friendly, and have enough perseverance, bicycle or hiking is also a good choice ,.

In software development, we often encounter similar situations,There are multiple ways to implement a function, each of which corresponds to an algorithm. In this case, we can use a design pattern to flexibly choose a solution, it can also easily add new solutions. This chapter introducesDesign Pattern generated to adapt to algorithm flexibility-policy pattern.

 

24.1 discount program for movie tickets

Sunny software company developed a cinema Ticketing System for a cinema, in which different types of users need to be given different discount methods for movie tickets. The specific discount scheme is as follows:

(1) students can enjoy a discount on the fare based on their student ID card;

(2) Children under 10 years of age can enjoy a 10 yuan discount per ticket (the original fare must be greater than or equal to 20 yuan );

(3) VIP cinema users can earn points in addition to half-price discounts on fares. Accumulated credits can be exchanged for prizes presented to cinemas.

The system may introduce new discounts as needed in the future.

In order to realize the Discount Function of movie tickets, sunny software company Developers designed a movieticket for movie tickets. The core code snippet is as follows:

// Movie ticket class movieticket {private double price; // movie ticket price private string type; // movie ticket type public void setprice (double price) {This. price = price;} public void settype (string type) {This. type = type;} public double getprice () {return this. calculate () ;}// calculate the discounted public double calculate () {// calculate the IF (this. type. equalsignorecase ("student") {system. out. println ("Student Pass:"); return this. price * 0.8;} // fare after discount for children LSE if (this. type. equalsignorecase ("children") & this. price> = 20) {system. out. println ("Children's Pass:"); return this. price-10;} // After VIP discount, the fare is calculated as else if (this. type. equalsignorecase ("VIP") {system. out. println ("VIP ticket:"); system. out. println ("add points! "); Return this. Price * 0.5;} else {return this. Price; // if no discount is required, the original fare is returned }}}

Write the following client test code:

Class client {public static void main (string ARGs []) {movieticket Mt = new movieticket (); double originalprice = 60.0; // The original fare double currentprice; // discount price Mt. setprice (originalprice); system. out. println ("Original Price:" + originalprice); system. out. println ("---------------------------------"); Mt. settype ("student"); // student ticket currentprice = Mt. getprice (); system. out. println ("discounted price:" + currentprice); system. out. println ("---------------------------------"); Mt. settype ("children"); // children's ticket currentprice = Mt. getprice (); system. out. println ("discounted price:" + currentprice );}}

Compile and run the program. The output result is as follows:

Original Price: 60.0

---------------------------------

Student Pass:

Discount price: 48.0

---------------------------------

Children's ticket:

Discount price: 50.0

Movieticket class is used to calculate the discount price of a movie ticket. This solution solves the discount problem of a movie ticket. Each discount method can be called a discount algorithm, to change the discount mode, you only need to modify the parameters in the client code without modifying the existing source code. However, this solution is not a perfect solution. It has at least three problems:

(1) The Calculate () method of the movieticket class is very large. It contains the implementation code of various discount algorithms, and a long if... Else... Statement is not conducive to testing and maintenance.

(2) When a New Discount algorithm is added or the original discount algorithm is modified, the source code of the movieticket class must be modified. This violates the "open and closed principle" and the system has poor flexibility and scalability.

(3) Poor reusability of algorithms. If you need to reuse some discount algorithms in another system (such as the mall Sales Management System), you can only copy and paste the source code to reuse them, one or more algorithms cannot be reused separately (it is troublesome to reuse ).

How can we solve these three problems? The main cause of these problems is that the movieticket class is too busy. It defines various discount algorithms in one class, which is neither easy to reuse nor easy to expand algorithms. Therefore, we need to refactor the movieticket class to break down the responsibilities of the huge movieticket class,Separate algorithm definition and usageThis is the problem to be solved by the Policy mode. The following describes how to learn the policy mode.

[Author: Liu Wei http://blog.csdn.net/lovelion]

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.