C # Design pattern (20)--Strategist mode (stragety pattern)

Source: Internet
Author: User

Original: C # design pattern (20)--Strategist mode (stragety pattern)

First, Introduction

The state pattern described in the previous topic is an abstraction of the state of an object, and the policy pattern to be introduced in this article is to abstract the strategy, which means the method, so that is the abstraction of the method, the following specific share of my understanding of the strategy model.

II. Strategy Model Introduction 2.1 definition of the policy model

In real life, examples of strategic patterns are also very common, for example, China's income tax, is divided into corporate income tax, foreign-invested enterprises or foreign enterprise income tax and personal income tax, for each of the 3 kinds of income tax, for each, the method of calculation, personal income tax has a personal income tax calculation method, And the enterprise income tax has its corresponding calculation way. If you do not adopt a policy model to achieve such a requirement, perhaps we will define an income tax class that has an attribute to identify the type of income tax and a calculatetax () method that calculates the tax, in which the tax type needs to be judged, The If-else statement is adopted to calculate the income tax for different tax types. Such an implementation can really solve this scenario, but such a design is not conducive to expansion, if the system needs to add a new income tax, at this time have to go back to modify the Calculatetax method to add a more judgment statement, so clear against the "open-closed" principle. At this point, we can consider using the strategy model to solve this problem, since the tax method is the changing part of this scene, it is natural to think of the tax method to abstract. The specific implementation code is shown in section 2.3.

The following describes the issues that the policy pattern solves, and gives a detailed definition of the policy. The policy pattern is for a set of algorithms that encapsulate each algorithm in a separate class with a common interface so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client.

2.2 Structure of the policy mode

The strategy pattern is the wrapper over the algorithm, which divides the responsibility of the algorithm and the algorithm itself, delegating it to different objects. The strategy pattern usually wraps a series of algorithms into a series of strategy classes. In a word, the policy pattern is--"encapsulate each algorithm into different policy classes so that they can be interchanged."

Here is the structure of the policy pattern:

  

The pattern involves three characters:

    • Environment Role (context): holding a reference to a strategy class
    • Abstract policy Role (strategy): This is an abstract role, usually implemented by an interface or abstract class. This role gives the interfaces that are required for all specific policy classes to be implemented.
    • Specific policy role (CONCRETESTRATEGY): wraps the associated algorithm or behavior.
2.3 Implementation of the policy model

The following is an example of income tax to implement the following policy model, the implementation code is as follows:

1 namespaceStrategypattern2 {3     //Income tax calculation Strategy4      Public Interfaceitaxstragety5     {6         DoubleCalculatetax (Doubleincome);7     }8 9     //Personal Income TaxTen      Public classpersonaltaxstrategy:itaxstragety One     { A          Public DoubleCalculatetax (Doubleincome) -         { -             returnIncome *0.12; the         } -     } -  -     //Corporate Income Tax +      Public classenterprisetaxstrategy:itaxstragety -     { +          Public DoubleCalculatetax (Doubleincome) A         { at             return(Income-3500) >0? (Income-3500) *0.045:0.0; -         } -     } -  -      Public classinterestoperation -     { in         Privateitaxstragety m_strategy; -          Publicinterestoperation (itaxstragety strategy) to         { +              This. M_strategy =strategy; -         } the  *          Public DoubleGettax (Doubleincome) $         {Panax Notoginseng             returnM_strategy. Calculatetax (income); -         } the     } +  A     classApp the     { +         Static voidMain (string[] args) -         { $             //personal Income Tax method $Interestoperation operation =NewInterestoperation (Newpersonaltaxstrategy ()); -Console.WriteLine ("the tax paid by the individual is: {0}", operation. Gettax (5000.00)); -  the             //Corporate Income Tax -Operation =NewInterestoperation (Newenterprisetaxstrategy ());WuyiConsole.WriteLine ("the tax paid by the enterprise is: {0}", operation. Gettax (50000.00)); the  - Console.read (); Wu         } -     } About}
Three, the strategist mode in. NET Applications

There are also examples of application of policy patterns in the. NET framework. For example, in. NET, the sorting functionality provided for collection types ArrayList and list<t>, where implementation takes advantage of the policy pattern, defines the IComparer interface to encapsulate the comparison algorithm, and the class that implements the IComparer interface can be sequential. Or to compare the size of two objects in reverse order, specifically. NET implementation can use the Anti-compilation tool to view the LIST<T>. The implementation of Sort (icomparer<t>). The list<t> is to assume the environment role, and the Icomparer<t> interface assumes the abstract strategy role, the concrete strategy role is realizes the Icomparer<t> interface the class,list<t> The class itself implements the class that implements the interface, and we can customize the specific policy classes that inherit the interface.

Iv. application scenarios for the strategist model

You can consider using the policy mode in the following scenarios:

    • A system needs to dynamically select one of several algorithms in the case. Then these algorithms can be packaged into a specific algorithm class, and provide a unified interface for these specific algorithm classes.
    • If an object has a lot of behavior, if you do not use the appropriate pattern, these behaviors will have to use multiple If-else statements to implement, at this time, you can use the policy mode, the behavior of these actions into the corresponding specific policy class, you can avoid the use of difficult to maintain multiple conditional selection statements, and embodies the concept of object-oriented.
V. Advantages and disadvantages of the strategist model

The key benefits of the strategy model are:

    • You can switch between policy classes freely. Because the policy classes implement the same interface, they are free to switch between them.
    • Easy to scale. Adding a new strategy requires only a specific policy class to be added, basically without changing the original code.
    • Avoid the use of multiple conditional selection statements, fully embodies the object-oriented design ideas.

The main drawbacks of the strategy model are:

    • The client must know all the policy classes and decide for themselves which policy class to use. This can be considered by using IOC containers and dependency injection, and articles about IOC containers and Dependency injection (Dependency Inject) can be consulted: IOC container and Dependency injection mode.
    • Policy mode causes a lot of policy classes.
Vi. Summary

Here, the introduction of the strategy mode is over, the strategy mode is mainly to encapsulate the method, encapsulate a series of methods into a series of policy classes, so that different policy classes can switch freely and avoid using multiple conditional selection statements in the system to choose different methods for different situations. In the next chapter, we will introduce the responsibility chain model.

C # Design pattern (20)--Strategist mode (stragety pattern)

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.