I. Overview
We come to realize a company's payroll system, the enterprise's different levels of staff wage algorithm is not the same, for this problem, the most easy to think of is in the code to accumulate a lot of if...else ... Statement or Switch...case ... Statement. If there are too many employees at different levels in the enterprise, or if the level is adjusted more frequently, then the system will appear complex and fragile. How can the object and the algorithm be decoupled, so that the system can transparently change the algorithm when it is running? This is the time for the strategy model to kick in.
Second, the Strategy model
The policy pattern defines a series of algorithms that 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.
The structure diagram of the policy mode is as follows:
The context represents the object that needs to change the algorithm, maintains a reference to the Strategy object, and can define an interface that allows the strategy object to access its data.
Strategy defines the public interface of the supported algorithm, which is used by the context to invoke the algorithm defined by the Concretestrategy.
The concretestrategy implements a specific algorithm.
Iii. examples
Below we use the policy model to implement the enterprise payroll system mentioned at the beginning of this article.
Define the public interface of the algorithm first
Public Interface Salary { int caculator (); }
Then implement the specific algorithm
Public class managersalary:salary { publicint caculator () { return; } } Publicclass employeesalary:salary { public int caculator () { return; } }
Then define the object that needs to dynamically change the algorithm.
Public class Employee { public Salary Salary {get; Set;} Public Employee (Salary Salary) { = salary; } Public int getsalary () { return salary.caculator (); } }
Finally look at how to invoke
static void Main (string [] args) {Employee employee = new Employee (new Employeesalary ()); Console.WriteLine ( employee salary is: {0} " , employee. Getsalary (). ToString ()); Employee. Salary = new Managersalary (); Console.WriteLine ( employee salary is: {0} " , employee. Getsalary (). ToString ()); Console.ReadLine (); }
This article from the network of related finishing, feel easy to understand, and share with you!
Strategy Mode of design pattern