I. Overview
Let's implement an enterprise's wage system. There are different employee wage algorithms of different levels in the enterprise. To solve this problem, the easiest thing to think of is to pile up a lot of if... Else... Statement or switch... Case... Statement. If there are too many employees at different levels in the enterprise, or the adjustment to the level is frequent, the system will become complex and fragile. How can we decouple objects and algorithms so that the algorithms of objects can be transparently changed during system operation? This is the time for the strategic model to show its talents.
Ii. Policy Mode
Policy patterns define a series of algorithms, encapsulate them one by one, and make them replaceable. This mode allows algorithms to change independently of customers who use it.
The structure of the Policy mode is as follows:
Context represents the object that needs to change the algorithm. It 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 interfaces that support algorithms. Context uses this interface to call the algorithms defined by ConcreteStrategy.
ConcreteStrategy implements specific algorithms.
Iii. Example
The following uses the policy model to implement the enterprise wage system mentioned at the beginning of this article.
First, define the public interface of the algorithm.
1 public interface Salary
2 {
3 int Caculator ();
4}
Then implement the specific Algorithm
1 public class ManagerSalary: Salary
2 {
3 public int Caculator ()
4 {
5 return 1000;
6}
7}
8
9 public class EmployeeSalary: Salary
10 {
11 public int Caculator ()
12 {
13 return 800;
14}
15}
Then define the object that needs to dynamically change the algorithm
1 public class Employee
2 {
3 public Salary {get; set ;}
4 public Employee (Salary salary)
5 {
6 Salary = salary;
7}
8 public int GetSalary ()
9 {
10 return Salary. Caculator ();
11}
12}
Finally, let's take a look at how to call
1 static void Main (string [] args)
2 {
3 Employee employee = new Employee (new EmployeeSalary ());
4 Console. WriteLine ("Employee salary is: {0}", employee. GetSalary (). ToString ());
5 employee. Salary = new ManagerSalary ();
6 Console. WriteLine ("Employee salary is: {0}", employee. GetSalary (). ToString ());
7
8 Console. ReadLine ();
9}
From saville
<Script> </script>