Design Patterns Strategy Pattern

Strategy Pattern
  objects have a certain behavior , but in different scenarios , the behavior has a different algorithm . For example, a person
  It is to prepare a set of algorithms, and the set of packages to a series of algorithms which policy class as a subclass of abstract class policy. 

The main solution
in a variety of algorithms similar circumstances, the use of complex and cumbersome nature if ... else or switch ... case brings.

Abstract Strategy (Strategy) category:
defines a common interface to a variety of different algorithms in different ways this interface,
    environment, the role of this interface calls using different algorithms, generally use interface or abstract class implements.

Specific strategies (Concrete Strategy) category:
implement the policy definition of abstract interfaces, provide specific algorithm.
: Environment (Context) class
references hold a policy class, and ultimately to the client calls.
 1 public class Strategy {
 2     public static void main(String[] args) {
 3         Context context = new Context(new add());
 4         int i = context.toCalculate(1, 2);
 5         System.out.println(i);
 6     }
 7 }
 8 
 9 //抽象策略
10 abstract class calculate {
11     public abstract int toCalculate(int a, int b);
12 }
13 
14 //具体策略
15 class add extends calculate {
16     @Override
17     public int toCalculate(int a, int b) {
18         return a + b;
19     }
20 }
21 
22 class sub extends calculate {
23     @Override
24     public int toCalculate(int a, int b) {
25         return a - b;
26      }
 27  }
 28  
29  // environment 
30  class the Context {
 31 is      // package strategy 
32      Private the Calculate CAL;
 33 is  
34 is      public the Context (the Calculate CAL) {
 35          the this .cal = CAL;
 36      }
 37 [  
38 is      public  int toCalculate ( int A , int B) {
 39          return cal.toCalculate (A, B);
 40      }
 41 is }

Guess you like

Origin www.cnblogs.com/loveer/p/11286075.html