What are strategic patterns?
The policy pattern belongs to the behavior pattern of an object. The idea is to take a set of algorithms and encapsulate each one into a separate class with a common interface, making them interchangeable. The policy pattern allows the algorithm to change without affecting the client.
What’s an example?
General code implementation
// First switch(" trip ") {case "bullet ": {" bullet"! ; break; } case "airplane ": {" airplane!" ; break; } case "train ": {" train!" ; break; } case "car ": {" car ": { ; break; } default: {" blah blah blah blah "; break; } // if(" travel mode "==" bullet train ") {" Bullet train!" ; } if(" travel mode "==" plane ") {" by plane!" ; } if(" travel mode "==" train ") {" By train!" ; } if(" mode of travel "==" car ") {" car!" ; }Copy the code
Implement 1) write an interface
interface TravelOutside {
void modeOfTravel();
}
Copy the code
2) Interface implementation
Public class implements TravelOutside {@override public void modeOfTravel() { System. Err. Println (" high-speed rail "); }} public class Aircraft implements TravelOutside {@override public void modeOfTravel() { System. Err. Println (" aircraft "); }} public implements TravelOutside {@override public void modeOfTravel() {system.err.println (" implements "); }} public class implements TravelOutside {@override public void modeOfTravel() { System. Err. Println (" car "); }}Copy the code
3) Abstract class implementation
Public class Travel {// TravelOutside TravelOutside; Public void setTravelOutside(TravelOutside TravelOutside) {this. TravelOutside = TravelOutside; } / / choose transportation public void travelStyle () {travelOutside. ModeOfTravel (); }}Copy the code
4) use
public static void main(String[] args) {
Travel travel = new Travel();
travel.setTravelOutside(new Aircraft());
travel.travelStyle();
}
Copy the code
Console output
conclusion
The policy mode involves three roles: Context: Defines an environment role, interacts with a specific policy class, and holds a reference to the policy class for the client to invoke. Abstract policy roles (Strategy) : Define abstract policy roles, usually implemented using interfaces or abstract classes. ConcreteStrategy roles: define ConcreteStrategy roles (in defining concrete strategies for airplanes, high-speed trains, trains, automobiles).