Source Address: http://blog.csdn.net/lovelion/article/details/7819136
Rule mode Overview
In policy mode, we can define some independent classes to encapsulate different algorithms. Each class encapsulates a specific algorithm. Here, every class that encapsulates algorithms can be called a strategy. To ensure consistency of these policies in use, an abstract policy class is generally provided for rule definition, each algorithm corresponds to a specific policy class.
The main purpose of the Policy mode is to separate the definition and use of an algorithm, that is, to separate the behavior and environment of an algorithm, and to put the definition of an algorithm in a specialized policy class, each strategy class encapsulates an implementation algorithm. The environment class of the algorithm is used to program the abstract strategy class and complies with the "Dependency inversion principle ". When a new algorithm appears, you only need to add a new specific policy class that implements the abstract policy class. The rule mode is defined as follows:
Strategy pattern: defines a series of algorithm classes, encapsulates each algorithm, and allows them to replace each other. The policy pattern allows algorithms to change independently of customers who use it, it is also called a policy ). Policy mode is an object behavior mode.
When using the Policy mode, We need to extract the algorithm from the context class. First, we should create an abstract policy class. The typical code is as follows:
Abstract class abstractstrategy {public abstract void algorithm (); // declare an abstract algorithm}
Then, the class that encapsulates each specific algorithm is used as a subclass of the abstract policy class, as shown in the following code:
Class concretestrategya extends abstractstrategy {// specific implementation of the algorithm public void algorithm () {// algorithm }}
The context class establishes an association between it and the abstract policy class. The typical code is as follows:
Class context {private abstractstrategy strategy; // maintain a reference to the abstract policy class public void setstrategy (abstractstrategy Strategy) {This. strategy = strategy;} // call the Public void algorithm () {strategy. algorithm ();}}
Define a strategy object of the abstractstrategy type in the context class, and input a specific policy object in the client through injection. The client code snippets are as follows:
Public class client {public static void main (string ARGs []) {context = new context (); abstractstrategy strategy; Strategy = new concretestrategya (); // you can specify the context type during runtime. setstrategy (Strategy); context. algorithm ();}}