Policy ModeThe algorithm family is defined, packaged separately, so that they can be replaced by each other, and this pattern allows the algorithm to change independently of the customer using the algorithm.
Description
:1, can dynamically change the behavior of the object, 2, the equality of each strategy algorithm, the implementation of each strategy algorithm is independent of each other, there is no dependence on each other (thus, the policy model can also be described as "
policy algorithms are different implementations of the same behavior3, during the operation, the strategy mode at a certain moment, can only use a specific strategy algorithm to implement the object, although it can dynamically change the behavior of the object, but also can only use one; 4, the policy mode can be very simple extension of the new implementation algorithm. Method: First write a strategy algorithm to implement the new requirements, and then specify the implementation algorithm when the client is used; 5. Multiple if-elseif statements represent an equal functional structure, you either execute if, or you do else, or ElseIf, at this time, Implementations within the IF block and other implementations within the Else block are equal in terms of operational status. The strategy pattern is to encapsulate the specific implementations of each equality into a separate policy implementation class, and then interact with the specific policy classes through the context. Therefore, multiple IF-ELSE statements can consider using policy mode.
Scene:1, the quotation management system, for the sales department of People, to different customers reported different prices. such as: For ordinary users or new users, the full price, the old customers quoted prices, a unified discount of 5%, the price of large customers quoted, a unified discount of 10%. Implementation: A: Define the Policy interface
/** * strategy, define the interface of calculation quoting algorithm */ Public interface Strategy { /** * Calculate the quoted price * @param goodsprice Commodity sales price * @return calculated, the price should be quoted to the customer */ Public double CalcPrice (double goodsprice); } |
B: Specific implementation of the various quotation criteria
| /** * specific algorithm implementation, Calculate the quoted price for a new customer or a regular customer */ Public class Normalcustomerstrategy implements strategy{ public double CalcPrice (double goodsprice) { System. Out . println ("No discount for new or regular customers"); return goodsprice; } } |
| /** * specific algorithm implementation, Calculate the quoted price for the old customer */ Public class Oldcustomerstrategy implements strategy{ Public double CalcPrice (double goodsprice) { System. Out . println ("For old customers, unified discount 5%"); return goodsprice* (1-0.05); } } |
/** * Specific algorithm implementation, for large customers to calculate the price to be quoted */ public class Largecustomerstrategy implements strategy{ Public double CalcPrice (double goodsprice) { System. out. println ("For big customers, unified discount 10%"); Return goodsprice* (1-0.1); } } |
C: Price class, the implementation of the context
/** * Price management, mainly to complete the calculation of the price quoted to the customer function */ public class Price { /** * Hold a specific policy object */ Private strategy strategy = NULL; /** * Construct a method to pass in a specific policy object * @param astrategy specific policy objects */ Public Price (strategy astrategy) { This.strategy = Astrategy; } /** * quote, calculate quote for customer * @param goodsprice Commodity sales price * @return calculated, the price should be quoted to the customer */ Public double quote (double goodsprice) { Return This.strategy.calcPrice (Goodsprice); } } |
D: Write a client to test
public class Client { public static void Main (string[] args) { 1: Select and create the policy object you want to use Strategy strategy = new Largecustomerstrategy (); 2: Create context Price CTX = new Price (strategy); 3: Calculate Quote Double quote = ctx.quote (1000); System. out. println ("Quote to Customer:" +quote); } } |
2, fault-tolerant recovery mechanism. When the program runs, it should normally be done in some way, if you do it in some way, the system will not crash, it will not be able to continue to run down, but the ability to tolerate errors, not only to tolerate errors in the program, but also to provide alternatives after the error, that is, the recovery mechanism To replace the normal execution of the function, so that the program continues to run down. For example, in a system, all the operation of the system must have a log record, and this log also need to have a management interface, in this case, the log is usually recorded in the database, easy to follow the management, but when logging to the database, there may be errors, such as temporarily not connected to the database, Then it is recorded in the file, and then at the appropriate time, the records in the file are transcribed into the database. You can use the policy mode to log the logs to the database and log records to a file as two logging policies, and then dynamically switch between them as needed during the run. (1) First define the log policy interface, very simple, is a method of logging, the sample code is as follows:
/** * Interface for logging policies */ Public interface Logstrategy { /** * Record Log * @param msg log information to be logged */ public void log (String msg); } |
(2) Implement the Log policy interface, first implement the default database implementation, assuming that if the length of the log is more than the length of error, manufacturing error is one of the most common run-time error, the sample code is as follows:
/** * Log logging to the database */ public class DbLog implements logstrategy{ public void log (String msg) { //Manufacturing error if (Msg!=null && Msg.trim (). Length () >5) { int a = 5/0; } System. out. println ("Now put '" +msg+ "in the Database"); } } |
Next implement logging to the file, the sample code is as follows:
/** * Log records to a file */ public class FileLog implements logstrategy{ public void log (String msg) { System. out. println ("Now put '" +msg+ "in File"); } } |
(3) Next define the context in which these policies are used, note that this is the choice of implementing a specific policy algorithm within the context, so there is no need for the client to specify a specific policy algorithm, the sample code is as follows:
(4) Look at the current client, there is no choice to implement the implementation of the strategy algorithm of the work, become very simple, deliberately multiple calls, you can see different effects, the sample code is as follows:
Reference: "Head first design mode" http://www.uml.org.cn/sjms/201009092.asp
The strategy mode of learning notes in design mode