C # design mode (20) -- rule mode (Stragety Pattern)

Source: Internet
Author: User

C # design mode (20) -- rule mode (Stragety Pattern)
1. Introduction The State mode introduced in the previous topic is the abstraction of the state of an object. The policy mode to be introduced in this article is the abstraction of the policy, and the policy means the method, this is the abstract of the method. The following describes my understanding of the policy mode. II. Introduction to the rule-by-strategy model 2.1 the definition of the policy model is in real life, and examples of the policy model are also very common, such as China's income tax, it can be divided into enterprise income tax, foreign-invested enterprises or foreign-invested enterprises income tax and personal income tax. For these three types of income tax, personal income tax is calculated in different ways, enterprise Income Tax has its own calculation method. If we do not use the policy mode to implement such a demand, we may define an income tax class, which has an attribute to identify the income tax type and has a CalculateTax () for tax calculation () in this method, you need to determine the tax type and use the if-else statement to calculate the income tax for different tax types. Can this implementation solve this scenario, but this design is not conducive to expansion. If the system needs to add an income tax later, it has to go back and modify the CalculateTax method to add another judgment statement, in this way, we understand that it violates the principle of "openness-closeness. At this point, we can consider using the policy model to solve this problem. Since the tax method is a change in this scenario, we can naturally think of abstracting the tax method. For specific implementation code, see Section 2.3. We have introduced the problem solved by the Policy mode. The policy definition is given below. Policy mode encapsulates an algorithm into an independent class with a public interface for mutual replacement. The policy mode allows the algorithm to change without affecting the client. 2.2 The structure policy mode of the Policy mode is the packaging of the algorithm. It separates the responsibility for using the algorithm from the algorithm itself and delegates the responsibility to different objects. The rule mode typically wraps a series of algorithms into a series of policy classes. In a single sentence, the rule mode is-"encapsulate each algorithm into different policy classes so that they can be exchanged ". Environment role (Context): holds a Strategy class referenced abstract policy role (Strategy): This is an abstract role, usually implemented by an interface or abstract class. This role provides all the interfaces required by the specific policy class. ConcreteStrategy: encapsulates related algorithms or actions. 2.3 The Implementation of the Policy mode is as follows: copy code 1 namespace StrategyPattern 2 {3 // income tax calculation policy 4 public interface ITaxStragety 5 {6 double CalculateTax (double income); 7} 8 9 // Personal income Tax 10 public class PersonalTaxStrategy: ITaxStragety11 {12 public double CalculateTax (double income) 13 {14 return income * 0.12; 15} 16} 17 18 // Enterprise income Tax 19 public class incluisetaxstrategy: ITaxStragety20 {21 public doub Le CalculateTax (double income) 22 {23 return (income-3500)> 0? (Income-3500) * 0.045: 0.0; 24} 25} 26 27 public class InterestOperation28 {29 private ITaxStragety m_strategy; 30 public InterestOperation (ITaxStragety strategy) 31 {32 this. m_strategy = strategy; 33} 34 35 public double GetTax (double income) 36 {37 return m_strategy.CalculateTax (income ); 38} 39} 40 41 class App42 {43 static void Main (string [] args) 44 {45 // Personal Income Tax method 46 InterestOperation operation = n Ew InterestOperation (new PersonalTaxStrategy (); 47 Console. writeLine ("personal payment tax: {0}", operation. getTax (5000.00); 48 49 // Enterprise Income Tax 50 operation = new InterestOperation (new EnterpriseTaxStrategy (); 51 Console. writeLine ("Enterprise payment tax: {0}", operation. getTax (50000.00); 52 53 Console. read (); 54} 55} 56} copy code 3. The policyholder mode is in.. NET. NET Framework also has examples of application of policy mode. For example. NET, which provides sorting functions for the set types of ArrayList and List <T>. The implementation uses the policy mode and defines the IComparer interface to encapsulate the comparison algorithm, classes that implement the IComparer interface can be sequential or reverse-order comparison of the sizes of the two objects. NET, you can use the decompilation tool to view the List <T>. implementation of Sort (IComparer <T>. List <T> assumes the environment role, while the IComparer <T> interface assumes the abstract policy role. The specific policy role is the class that implements the IComparer <T> interface, the List <T> class itself implements the class that implements this interface. We can customize the specific policy class inherited from this interface. 4. Use the rule mode in the following scenarios: A system must dynamically select one of several algorithms. These algorithms can be encapsulated into specific algorithm classes and provide a unified interface for these specific algorithm classes. If an object has many behaviors and the appropriate mode is not used, these behaviors must be implemented using multiple if-else statements. In this case, you can use the policy mode, by transferring these actions to the corresponding specific policy class, you can avoid using multiple conditional selection statements that are difficult to maintain and reflect the concept of object-oriented. 5. Advantages and disadvantages of the policymaker mode the main advantages of the Policy mode are: the Policy classes can be freely switched. Because the policy classes all implement the same interface, they can switch between them freely. Easy to expand. To add a new policy, you only need to add a specific policy class. Basically, you do not need to change the original code. Avoid using multiple conditional selection statements to fully reflect the object-oriented design philosophy. The main disadvantages of the Policy mode are that the client must know all the policy classes and decide which policy class to use. This can be solved using IOC containers and Dependency Injection methods. For more information about IOC containers and Dependency Injection (Dependency Inject), See IoC containers and Dependency Injection mode. The rule mode may cause many policy classes. 6. To sum up, the introduction of the policy mode is over. The policy mode encapsulates methods and encapsulates a series of methods into a series of policy classes, so that different policy classes can switch freely and avoid using multiple Condition Selection statements in the system to select different methods for different situations. In the next chapter, we will introduce the responsibility chain model.

Related Article

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.