Algorithm encapsulation and switching-policy mode (4)

Source: Internet
Author: User
24.4 two typical applications of policy Mode

The policy mode is highly practical and scalable and widely used in software development. It is one of the most frequently used design modes. The following describes two typical application instances of policy mode, one fromJava SE, A demo project from MicrosoftPetshop.

(1) The container layout management of Java SE is a classic application instance of the Policy mode. Its basic structure is 24-3:


[Every time I see this layoutmanager2 interface, I wonder what Sun developers thought at the time !]

In Java SE development, you need to layout the Member objects, such as buttons and text boxes, in the container object container ), during the program running, the client dynamically determines how a container object is laid out. Java provides several different layout methods in JDK and encapsulates them in different classes, such as borderlayout, flowlayout, gridlayout, gridbaglayout, and cardlayout. In Figure 24-3, the container class acts as the context role, while layoutmanager acts as the common parent class of all layout classes as the abstract policy role. It provides the interfaces required for all specific layout classes, specific policy classes are subclasses of layoutmanager, that is, various specific layout classes, which encapsulate different layout methods.

Anyone can design and implement their own layout classes. They only need to use their own layout classes as subclasses of layoutmanager. For exampleLegendary Borland Company (now a legend ,)In JBuilder, a new layout method called xylayout was provided as a supplement to the layout class provided by JDK. For the client, you only need to use the setlayout () method provided by the iner class to set any specific layout mode without worrying about the specific implementation of the layout. In JDK, the code snippet of the container class is as follows:

public class Container extends Component {    ……    LayoutManager layoutMgr;    ……    public void setLayout(LayoutManager mgr) {layoutMgr = mgr;……    }    ……}

From the code above, we can see that as an environment class, container is programmed for the abstract policy class layoutmanager. When using it, you only need to set the setlayout () you do not need to worry about its implementation.

(2) In addition to Java-based applications, policy models are also widely used in software developed using other object-oriented technologies.

In the demonstration project petshop 4.0 provided by Microsoft, the policy mode is used to process synchronous orders and asynchronous orders. In the business logic layer (BLL) sub-project of petshop 4.0, there is an orderasynchronous class and an ordersynchronous class. They all inherit from the iorderstrategy interface, as shown in 24-4:

In Figure 24-4, ordersynchronous processes orders in a synchronous manner, while orderasynchronous stores orders in a queue before processing orders in the queue, process orders in an asynchronous manner. The bll order class reads policy configuration information from the configuration file through the reflection mechanism to determine which order processing method is used. The code snippet in the configuration file web. config is as follows:

……<add key="OrderStrategyClass" value="PetShop.BLL.OrderSynchronous"/>……

You only need to modify the configuration file to change the order processing method, which improves the system flexibility.

 

24.5 Summary of policy Modes

The policy mode is used to freely switch and expand algorithms. It is one of the more widely used design modes. The policy mode corresponds to an algorithm family that solves a problem. You can select an algorithm from this algorithm family to solve a problem, at the same time, you can easily change the algorithm or add new algorithms. Policy modes can be considered as long as the algorithm encapsulation, reuse, and switching are involved.

1. Main advantages

The main advantages of the Policy mode are as follows:

(1) The policy mode provides perfect support for the "open and closed principle". You can select algorithms or actions without modifying the original system, you can also flexibly add new algorithms or actions.

(2) The policy mode provides methods for managing related algorithm families. The hierarchical structure of a policy class defines an algorithm or behavior family. With proper inheritance, you can move public code to the abstract policy class to avoid repeated code.

(3) The policy mode provides a way to replace the inheritance relationship. If the policy mode is not used, the Environment class using the algorithm may have some subclasses. each subclass provides a different algorithm. However, in this way, the algorithm is used together with the algorithm itself, and does not comply with the "single responsibility principle". The logic of the algorithm used is determined to be mixed with the algorithm itself, therefore, it is impossible to evolve independently. In addition, inheritance cannot implement dynamic switching of algorithms or behaviors during the running of programs.

(4) using policy mode can avoid multiple Condition Selection statements. The multi-condition selection statement is not easy to maintain. It combines the logic of the algorithm or behavior with the Implementation logic of the algorithm or behavior, and hard coding all of them) in a large multi-condition selection statement, it is more primitive and backward than simply inheriting the environment class.

(5) The policy mode provides an algorithm reuse mechanism. Because the algorithms are extracted separately and encapsulated in the Policy class, these policy classes can be easily reused in different environments.

2. Main disadvantages

The main disadvantages of the Rule mode are as follows:

(1) The client must know all the policy classes and decide which one to use. This means that the client must understand the differences between these algorithms so that appropriate algorithms can be selected in a timely manner. In other words, the policy mode is only applicable when the client knows all the algorithms or actions.

(2) The policy mode will generate many specific policy classes in the system, and any small changes will lead to a new specific policy class in the system.

(3) You cannot use multiple policy classes on the client at the same time. That is to say, when using the Policy mode, the client can only use one policy class at a time, it is not supported to use one policy class to complete some functions and then use another policy class to complete the remaining functions.

3. Applicable scenarios

You can consider using the Policy mode in the following situations:

(1) If a system needs to dynamically select one of several algorithms, these algorithms can be encapsulated into specific algorithm classes, these specific algorithm classes are subclasses of an abstract algorithm class. In other words, these specific algorithm classes have a unified interface. Based on the "Lee's replacement principle" and object-oriented polymorphism, the client can choose to use any specific algorithm class, you only need to maintain an object whose data type is an abstract algorithm class.

(2) An object has many behaviors. If an appropriate mode is not used, these behaviors must be implemented using multiple conditional selection statements. In this case, the policy mode is used to transfer these actions to the corresponding specific policy class, so that you can avoid using the multi-Condition Selection statements that are difficult to maintain.

(3) You do not want the client to know the complex and algorithm-related data structures. Encapsulating algorithms and related data structures in specific policy classes can improve the confidentiality and security of algorithms.

 

Exercise

Sunny software wants to develop an aircraft simulation system that simulates the flight characteristics and Take-off Characteristics of different types of aircraft. The types and characteristics of aircraft to be simulated are shown in Table 24-1:

Table 24-1 aircraft types and features

Aircraft Types

Takeoff features

Flight features

Helicopter)

Verticaltakeoff)

Subsonicfly)

Airplane)

Longdistancetakeoff)

Subsonicfly)

Fighter (fighter)

Longdistancetakeoff)

Supersonicfly)

Harrier)

Verticaltakeoff)

Supersonicfly)

To simulate more types of aircraft in the future, we try to design the aircraft Simulation System in a strategy 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.