In the previous article (the application of OOP design process Evolution (ii)) to improve the entire system architecture, as well as the completion of the functions of each specific function, this can only be completed a structure, to truly perfect still very far. For example, in calculating the rent of the algorithm, using a switch statement to determine the type of books to determine the book discount, before I in order to demonstrate in the switch statement fixed the discount algorithm policy, the following code schematic code:
1/**//// <summary>
2/// 计算租金
3/// </summary>
4/// <returns></returns>
5private double GetRent()
6{
7 switch (_bType)
8 {
9 case B_Type.NOVEL: BookCash = Convert.ToDouble(Day) * 0.1;
10 break;
11 case B_Type.LIFT: BookCash = Convert.ToDouble(Day) * 1d;
12 break;
13 case B_Type.MAGAZINE: BookCash = Convert.ToDouble(Day) * 0.5;
14 break;
15 }
16 return BookCash;
17}
This is the original design of the ordinary customers borrow discount algorithm, rented is a novel, Rent discount *0.1, Life Books rent discount *1, while the magazine is playing 50 percent, it is obvious that such a curing design is unreasonable, then how should we solve it? , in the actual application development, we should read these discount rates from the database or the configuration file, below I read the way from the configuration file briefly.
We can analyze this, because the discounts for different types of books are not the same, there are two other roles in the system (members and ordinary customers), then the discount rate of members and the average customer discount rate should also be different, we should define different algorithms for them, each discount algorithm encapsulated into a class, Then we just have to decide which class to use (the specific policy object) to process according to the type of book. With this analysis, the policy pattern (strategy) is the pattern for solving the problem, which is defined as "preparing a set of algorithms and encapsulating each one so that they can be interchanged." "
The use of policy patterns is initiated by the user and determines what specific policy roles to use depending on the user's actions. In other words, we can use this model to solve the above curing discount algorithm. The type of books in the system is divided into three categories: fiction, life and magazines; we can define a separate algorithm strategy for each of the three types of books, and of course we can define these three strategies into a class. Since we are object-oriented programming, let's just keep it separate. But keep in mind that "object-oriented programming is not the more class the better, the class is divided to encapsulate, but the classification is based on abstraction, the same attributes and functions of the abstract collection of objects is the class." "If you can do that in a real project, it's enough, and the division of the class depends on the actual requirements."