Rule mode-3

Source: Internet
Author: User
ArticleDirectory
    • 3.1 recognition policy model
    • 3.2 Fault Tolerance recovery mechanism

Author: Yunfei Longxing published on read: 861 comments: 1

3 mode explanation 3.1 recognition policy Mode

(1) functions of policy Mode
The policy mode function is to take the specificAlgorithmImplement, independent from specific business processing, and implement them into separate algorithm classes to form a series of algorithms and make these algorithms replace each other.
The focus of the policy mode is not how to implement algorithms, but how to organize and call these algorithms to makeProgramThe structure is more flexible, with better maintainability and scalability.

(2) Policy mode and if-else statement
After reading the previous example, many friends will find that the specific implementation function of each policy algorithm is the original implementation in the IF-else structure.
Yes, in fact, multiple if-elseif statements express an equal functional structure. You can either execute if, or you can execute else or elseif. At this time, the implementation in the IF block is equal to that in the else block in terms of running status.
The policy mode encapsulates the specific implementation of equality into a separate policy implementation class, and then interacts with the specific policy class through context.
Therefore, the policy mode can be considered for multiple if-else statements.

(3) Equality of Algorithms
A major feature of the policy model is the equality of each policy algorithm. For a series of specific policy algorithms, everyone has the same status. It is precisely because of this equality that algorithms can be replaced with each other.
All policy algorithms are independent of each other and are independent from each other.
Therefore, we can describe this series of policy algorithms as follows:Policy algorithms are different implementations of the same behavior.

(4) who should choose a specific policy algorithm?
In policy mode, you can select a specific policy in two places.
One is that when the context is used on the client, the client selects a specific policy algorithm and sets this policy algorithm to the context. This is the case in the previous example.
The other one is that the client does not care. The context selects specific policy algorithms. This will be demonstrated later when we talk about fault tolerance recovery.

(5) implementation of strategy
In the previous example, strategy is defined by interfaces, which is also a common implementation method. However, if multiple algorithms have public functions, You can implement strategy as an abstract class, and then implement the public functions of multiple algorithms into strategy.

(6) uniqueness of runtime policies
During running, the policy mode can only use one specific policy to implement objects at a time. Although it can be dynamically switched in different policy implementations, it can only use one.

(7) Add new policies
In the previous example, I realized the convenience of switching algorithms in the Policy mode, but what if I add a new algorithm? For example, the following features should be implemented: off for the company's "strategic partner customers.
In fact, it is very simple. The policy mode allows you to flexibly expand new algorithms. The specific method is: first write a policy algorithm class to meet new requirements, and then specify to use the new policy algorithm class when using the client.
It can be illustrated through examples. Add a policy class that meets the requirements.CodeAs follows:

/**

* Specific Algorithm Implementation: Calculate the quoted price for strategic partner customers

*/

Public class cooperatecustomerstrategy implements Strategy {

Public double calcprice (double goodsprice ){

System.Out. Println ("for strategic partner customers ");

Return goodsprice * 0.8;

}

}

Then, specify the new policy algorithm implementation when the client specifies the policy to be used. The example is as follows:

public class Client2 {

Public static void main (string [] ARGs) {

// 1: select and create the expected policy object

strategy Strategy = new cooperatecustomerstrategy ();

// 2: create context

price CTX = new price (Strategy );

// 3: calculate the quote

double quote = CTX. quote (1000);

system. out . println ("quoted to the customer:" + quote );

}

}

Except for some bold changes, the client has no other changes.

Run the client and test it.
In addition to client changes, the existing context, policy interface definition, and policy implementations do not need to be modified. It can be seen that new policy algorithms can be easily expanded.

(8) Rule mode Call Sequence
There are two common cases about the call sequence of the Rule mode, one is as follows:

A: First, the client selects and creates specific policy objects.

B: Then the client creates the context

C: Then the client can call the context method to execute the function. During the call, the client can pass in the parameters required by the algorithm.

D: when the context receives a call request from the customer, it will forward the request to its strategy.

The call sequence is as follows:

Figure 3 sequence 1 of policy mode calls

There is another case for calling the rule mode, that is, passing context as a parameter to strategy. The call sequence diagram in this way is provided when talking about the relationship between context and strategy.
 

3.2 Fault Tolerance recovery mechanism

Fault Tolerance recovery is a common feature in application development. So what is fault tolerance recovery? Simply put: when the program is running, it should be done in a certain way under normal circumstances. If an error occurs in a certain way, the system will not crash or continue to run down, it can tolerate errors. It can not only tolerate program running errors, but also provide a backup solution after errors, that is, a recovery mechanism, to replace normal execution functions, keep the program running down.
For example, in a system, all operations on the system must be logged, and the log must have a management interface, in this case, logs are usually recorded in the database to facilitate subsequent management. However, errors may occur when logs are recorded to the database, for example, the database cannot be connected temporarily, record the records in the file first, and then record the records in the file into the database when appropriate.
For the design of such functions, we can adopt the policy mode to record logs to the database and logs to files as two logging policies, then, perform a dynamic switchover as needed during running.
In the implementation of this example, we need to demonstrate how to select a specific policy algorithm from context. In the previous example, the client selects a specific algorithm and then sets it to context.
The following code is used as an example.
(1) first define the log policy interface, which is very simple. It is a log recording method. The sample code is as follows:

/**

* Log record policy interface

*/

Public interface logstrategy {

/**

* Logging

* @ Param MSG the log information to be recorded

*/

Public void log (string MSG );

}

(2) Implement the log policy interface. First, implement the default database implementation. If the log length exceeds the length, an error occurs. The most common runtime error is a manufacturing error. The sample code is as follows:

/**

* record logs to database

*/

public class dblog implements logstrategy {

Public void log (string MSG) {

// manufacturing error / p>

If (MSG! = NULL & MSG. trim (). length ()> 5) {

int A = 5/0;

}

system. out . println ("now record '" + MSG + "' to the Database ");

}

}

 

Next, we will record the logs to the file. The sample code is as follows:

/**

* Record logs to files

*/

Public class filelog implements logstrategy {

Public void log (string MSG ){

System.Out. Println ("now record '" + MSG + "' to file ");

}

}

 

(3) Next we will define the context for using these policies. Note that this time the specific policy algorithm is selected in the context, so the client does not need to specify the specific policy algorithm. The sample code is as follows:


 

(4) Look at the current client, without selecting the specific implementation of the Policy algorithm, it becomes very simple, deliberately call it once more, you can see different effects, the sample code is as follows:


 

(5) In summary, through the above example, we will see a simple application of the policy mode, and also take a look at the design and implementation of the basic fault tolerance recovery mechanism. In practical applications, systems that require fault tolerance and recovery generally have high requirements and complex applications, but the basic idea is similar.

 

 

 

To be continued ......

Comments: 1. view comments and post comments

Annual software R & D team management conference (Shanghai, 7.10-7.11)

Latest news:
· Run Ubuntu video display in hd2 again with WM)
· Apple launched its mobile advertising platform, Iads, with orders worth $60 million)
· 50 ultra-convenient tools provided by web designers (below))
· Municipal Adjustment Company: the global market share of IE browser has finally begun to rise)
Cisco promises to launch Flip cameras that support WiFi and video clients that support FaceTime)

Recommended for editing: domain-driven design practices

website navigation: blog home page personal homepage news flash team blog community knowledge base

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.