C # design Pattern 19 Policy pattern (stragety pattern) "Behavioral"

Source: Internet
Author: User

Original: C # design Pattern 19 Policy mode (stragety pattern) "Behavioral"

First, Introduction

Today we begin to talk about the seventh mode of "behavioral" design pattern, which is "strategy mode", the English name is: stragety pattern. In real life, examples of strategic patterns are also very common, for example, in a company, there will be a variety of staff, such as: some of the general staff, some software architects, some department managers, of course, there will be the CEO of the company. These staff are responsible for different tasks, and the responsibilities are different, and the rewards that are naturally paid are different. Each worker has his or her own salary, but the salary of each type of worker is not the same as the calculation method. If everyone's wages are the same, they will certainly chaos. If we do not adopt a policy model to implement this requirement, we may do so, we will define a payroll class that has a property to identify the type of worker, and a calculatesalary () method for calculating wages, in which the type of worker needs to be judged, The resulting salary is calculated for different worker types by using the If-else statement. Such an implementation can really solve this scenario, but such a design is not conducive to expansion, if the system later need to add a new type of work, at this time have to go back to modify the Calculatesalary method to add a more judgment statement, which clearly violates the "open-closed" principle. At this point, we can consider using the strategy model to solve this problem, since the salary calculation method is the change part of this scene, at this time naturally can think of the payroll algorithm abstraction, different types of wages can be used without the strategy of the implementation of the algorithm, want to get a worker's wages, It can be calculated by using its corresponding wage algorithm strategy.

Ii. Detailed introduction to the Strategy model

2.1. Motive (motivate)

In the process of software building, the algorithms used by some objects may be varied and often changed, and if these algorithms are encoded into objects, the objects will become unusually complex, and sometimes support for unused algorithms is a performance burden. How can I change the algorithm of an object transparently at run time, as needed? Decoupling the algorithm from the object itself to avoid these problems?

2.2. Intention (Intent)

Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other.                                      This pattern allows the algorithm to be independent of the customers who use it. --"Design pattern" GoF

2.3. Structure diagram (Structure)



2.4, the composition of the model

As you can see, the structure diagram in the policy mode has the following roles:

(1), Environmental Role (context):Holds a reference to a strategy class.

You need to use the algorithm provided by Concretestrategy.

Internally maintains an instance of strategy.

Responsible for dynamically setting the runtime strategy specific implementation algorithm.

Responsible for interaction and data transfer with strategy

(2), abstract policy role (strategy): Defines a common interface in which different algorithms implement this interface in different ways, and the context uses this interface to invoke different algorithms, which are generally implemented using interfaces or abstract classes.

(3), Specific strategy role (CONCRETESTRATEGY): Implements the interface defined by the strategy and provides a concrete algorithm implementation.

2.5, the code implementation of the policy mode

In real life, there are many examples of strategic patterns, such as: A company will have a lot of job types, each job type responsible for the work of different, naturally, the wage calculation method of each work will vary widely, today we use the calculation of wages as an example to illustrate the usage of the strategy model, we directly on the code, But don't do that in the actual code, we're going to use the pattern in an iterative way. The implementation code is as follows:

1 namespaceimplementation of the policy pattern2 {3     //Environment Role---equivalent to the context type4      Public Sealed classSalarycontext5     {6         Privateisalarystrategy _strategy;7 8          PublicSalarycontext (Isalarystrategy strategy)9         {Ten              This. _strategy =strategy; One         } A  -          Publicisalarystrategy isalarystrategy -         { the             Get{return_strategy;} -             Set{_strategy =value;} -         } -  +          Public voidGetsalary (Doubleincome) -         { + _strategy. Calculatesalary (income); A         } at     } -  -     //abstract Policy role---equivalent to strategy type -      Public InterfaceIsalarystrategy -     { -         //Payroll Calculation in         voidCalculatesalary (Doubleincome); -     } to  +     //Programmer's salary-equivalent to a specific strategy role Concretestrategya -      Public Sealed classProgrammersalary:isalarystrategy the     { *          Public voidCalculatesalary (Doubleincome) $         {Panax NotoginsengConsole.WriteLine ("My salary is: basic salary ("+ Income +") Basic salary ("+8000+") + Overtime + Project bonus (10%)"); -         } the     } +  A     //The average employee's salary---equal to the specific strategy role Concretestrategyb the      Public Sealed classNormalpeoplesalary:isalarystrategy +     { -          Public voidCalculatesalary (Doubleincome) $         { $Console.WriteLine ("My salary is: basic salary ("+ Income +") Basic Salary (3000) + Overtime"); -         } -     } the  -     //the CEO's salary---equivalent to a specific strategic role CONCRETESTRATEGYCWuyi      Public Sealed classCeosalary:isalarystrategy the     { -          Public voidCalculatesalary (Doubleincome) Wu         { -Console.WriteLine ("My salary is: basic salary ("+ Income +") Basic Salary (20000) + Project BONUS (20%) + Company stock"); About         } $     } -  -  -      Public classClient A     { +          Public Static voidMain (string[] args) the         { -             //salaries of ordinary employees $Salarycontext context =NewSalarycontext (Newnormalpeoplesalary ()); theContext. Getsalary ( the); the  the             //CEO's salary theContext. Isalarystrategy =Newceosalary (); -Context. Getsalary (6000); in  the Console.read (); the         } About     } the}

Three, the implementation of the strategy model points:

Strategy and its subclasses provide a series of reusable algorithms for the component, which allows the type to easily switch between the algorithms as needed at run time, so-called encapsulation algorithms that support the change of the algorithm. The strategy mode provides an alternative to conditional judgment statements, eliminating conditional judgments and decoupling. Code that contains many conditional judgment statements usually requires strategy mode.

Similar to state, if the strategy object does not have an instance variable, then each context can share a strategy object, saving object overhead. The strategy pattern is applicable to the entire algorithm in the algorithm structure, rather than the change of a part of the algorithm.

Template method: The step protocol that executes the algorithm is itself placed inside the abstract class, allowing a common algorithm to manipulate multiple possible implementations

Strategy mode: The protocol that executes the algorithm is in the specific class, each specific implementation has a different generic algorithm to do.

(1), the main advantages of the strategy model are:

1 ", the policy class can be free to switch between. Because the policy classes implement the same interface, they are free to switch between them.

2 ", easy to expand. Adding a new strategy requires only a specific policy class to be added, basically without changing the original code.

3 ", avoid the use of multiple conditional selection statements, fully embodies the concept of object-oriented design.

  (2), the main shortcomings of the strategy model are:

1 ", the client must know all of the policy classes and decide for itself 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.

2 ", policy mode will cause a lot of policy classes.

(3), in the following cases, you may consider using the policy mode:

1 ", 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.

2 ", 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.

Iv. implementation of the. NET Policy Model

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&LT;T&GT. 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.

v. Summary

It's a bit late today and it's late to finish. The strategy model is not very difficult, it can be said very simple, perhaps we have already used this pattern in the actual coding. The old adage is that we have to use every pattern clearly, to understand their pros and cons, and to understand the situations they use. We use patterns to remember not to use patterns, and we should write the code in an iterative way. When we encode, the first impression is very important, how to write for the first time, if there is a change in demand, and change more frequently, then we carefully analyze the change point, and then find the appropriate mode to solve the corresponding problem.

C # design Pattern 19 Policy pattern (stragety pattern) "Behavioral"

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.