The strategy pattern
introduce
1. A design pattern in which a behavior or its algorithm can be changed at run time is a strategic pattern. 2. In the policy mode, we create objects representing various policies and a Choose object whose behavior changes as the policy object changes, and the policy object changes the execution algorithm of the Choose object. 3. Test code github.com/644968328/D…
advantages
1. You can dynamically change the behavior of an object. 2. Avoid multiple conditional judgments. 3. Good scalability.
disadvantages
1. Many policy classes should be exposed. 2. The more policies, the more classes.
Application scenarios
1. If there are many classes in a system, the difference between them is their behavior, then using the policy pattern can dynamically let an object choose one behavior among many behaviors. 2. A system needs to dynamically select one of several algorithms. 3. If an object has many behaviors that need to be implemented using multiple conditional selection statements.
The structure
The implementation code
background
Git wants to travel, so it uses strategic mode to make a travel plan.
Step one
Create a policy interface with a method for the travel mode.
Public interface Strategy {public String travelWay(); public String travelWay(); public String travelWay(); }Copy the code
Step 2
Create a concrete implementation class for the policy that encapsulates each mode of travel.
/** * public implements Strategy {@override public StringtravelWay() {
return "Travel by Air"; }}Copy the code
/** * public class implements Strategy {@override public StringtravelWay() {
return "Travel by train"; }}Copy the code
/** * public implements Strategy {@override public StringtravelWay() {
return "Travel by car"; }}Copy the code
Step 3
Creates a policy runtime environment, equivalent to a policy selector class, that holds a reference to a policy interface.
/** * public class Choose {private Strategy Strategy; Public Choose(Strategy Strategy) {this.strategy = Strategy; } public StringtravelWay() {
returnstrategy.travelWay(); }}Copy the code
Step 4
Create demo and Run it
public class StrategyPatternDemo {
public static void main(String[] args) {
System.out.println("One day Git wanted to travel, so he made a route.");
Choose
planStrategy = new Choose(new PlaneStrategy()),
trainStrategy = new Choose(new TrainStrategy()),
carStrategy = new Choose(new CarStrategy());
System.out.println("He's going to go first." + planStrategy.travelWay() + "Visit Shanghai first.");
System.out.println("And then in"+trainStrategy.travelWay()+"To Hangzhou");
System.out.println("Last in."+carStrategy.travelWay()+"To the hotel"); }}Copy the code