definition
Define an algorithm, encapsulate each algorithm, and make them interchangeable. Is a kind of behavior pattern.
Examples
To make it easy to understand, we take the calculation of tax rates in various countries as an example:
Suppose currently our program can only support the calculation of tax rates in China and the United States:
1 public class Tax_Cal { 2 3 public int CN_Cal ( int x) { // calculate Chinese tax 4 5 } 6 7 public int US_Cal ( int x) { // calculate US tax 8 9 } 10 }
It seems no problem to write this way, but in fact we think about it, if the company needs to expand in the future and start to support France, Japan and other countries, then we have to constantly change this category, is it particularly troublesome and dangerous? For example, if there is a conflict with a previous country, it will affect the previous calculation.
Therefore, we write them separately and separate all national tax calculations. The implementation of the same interface all has a common parameter x.
1 public class Strategy { // strategy mode 2 public int Cal ( int x); 3 } 4 5 public class CN_Tax implements Strategy { // implement Chinese tax calculation interface 6 7 @Override 8 public int Cal ( int x) { 9 10 } 11 } 12 13 public class US_Tax implements Strategy { // implement US tax calculation interface 14 15 @jOverride 16 public int Cal ( int x) { 17 18 } 19 } 20 21 public class Tax_Cal { // tax calculation class 22 23 private Strategy = strategy; // define a strategy 24 25 public void setStrategy (Strategy strategy) { // Access strategy 26 this .strategy = strategy; 27 } 28 29 public int getTax (int x) { // Get the result 30 return this .strategy.cal 31 } 32 }
In this way, all tax calculations will not affect each other, because their calculations have been independent of us. To calculate the tax of which country, you only need to access the algorithm of that country and call getTax. Let's write:
1 public class Test { 2 public static void main (string [] args) { 3 Tax_Cal tax_cal = new Tax_Cal (); // instantiated object 4 tax_cal.setStrategy ( new CN_Tax ()); // access to Chinese tax calculation 5 int res = tax_cal.getTax (100); // Get the result 6 } 7 }
to sum up:
advantage:
1. You can switch freely between strategies because they all implement the same abstraction.
2. Easy to expand, basically can be expanded without changing the original code.
3. Avoid using multiple conditional statements, otherwise you have to keep if else, switch case, which is very unfavorable for maintenance.
Strategy mode is a simple and commonly used design mode. Generally, it is not used alone, but mixed with other modes.