java design pattern strategy pattern

1. The strategy mode is also called the algorithm family mode, which defines different algorithm families and can be replaced with each other. This mode makes the changes of the algorithm independent of the customers who use the algorithm. The advantage of the strategy pattern is that you can dynamically change the behavior of objects. The strategy pattern is suitable for use when an application needs to implement a specific service or function, and the program has multiple implementations.

2. Design principle: Extract the part of a class that changes frequently or may change in the future as an interface, and then includes an instance of the object in the class, so that the instance of the class can be called at will at runtime to implement this interface the behavior of the class.

There are three objects in the strategy pattern:

a. Environment object: This class implements a reference to the interface or abstract class defined in the abstract strategy

b. Abstract strategy object: it can be implemented by interface or abstract class

c. Specific strategy object: encapsulates the implementation

Abstract strategy object:

 

package com.yangguangfu.strategy;   
/**    
 * First define a strategy interface
 */  
public interface IStrategy {   
   //define this behavior
   public void operate();     
}  

 Specific policy objects:

 

 

/**    
* Implementation
*/  
public class BlackEnemy implements IStrategy {   
  
    @Override  
    public void operate() {   
        System.out.println("It's raining today, take a taxi home!");   
  
    }   
}  

 Environment object:

 

 

/**  
* Provides an environment with different strategies
*/  
public class Context {   
       
   private IStrategy strategy;   
    //Constructor, which trick you want to use   
    public Context(IStrategy strategy){   
        this.strategy = strategy;   
   }   
      
    public void operate(){   
       this.strategy.operate();   
   }   
}  

 TEST:

 

 

public class Test{

  public static void main(String[] args){
     Context context;
     //It's raining today! ! !
     context = new Context(new BlackEnemy());
     context.operate();
   }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327097241&siteId=291194637