Rule mode, java rule Mode
Public class TravelStrategy {enum Strategy {WALK, PLANE, SUBWAY} private Strategy strategy; public TravelStrategy (Strategy strategy) {this. strategy = strategy;} public void travel () {if (strategy = Strategy. WALK) {print ("walk");} else if (strategy = Strategy. PLANE) {print ("plane");} else if (strategy = Strategy. SUBWAY) {print ("subway") ;}} public void print (String str) {System. out. println ("travel mode:" + str);} public static void main (String [] args) {TravelStrategy walk = new TravelStrategy (Strategy. WALK); walk. travel (); TravelStrategy plane = new TravelStrategy (Strategy. PLANE); plane. travel (); TravelStrategy subway = new TravelStrategy (Strategy. SUBWAY); subway. travel ();}}
Obviously, if you need to increase the travel mode, you need to add a new else if statement, which violates one of the object-oriented principles and encapsulates the modification (the open and closed principle)
How can we solve this problem using the Policy mode?
① Define an interface for a policy:
public interface Strategy { void travel(); }
② Implement this interface based on different travel methods:
public class WalkStrategy implements Strategy{ @Override public void travel() { System.out.println("walk"); } }public class PlaneStrategy implements Strategy{ @Override public void travel() { System.out.println("plane"); } }public class SubwayStrategy implements Strategy{ @Override public void travel() { System.out.println("subway"); } }
③ A class of packaging policy is required to call the interface in the policy.
public class TravelContext { Strategy strategy; public Strategy getStrategy() { return strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public void travel() { if (strategy != null) { strategy.travel(); } } }
④ Test the Code:
public class Main { public static void main(String[] args) { TravelContext travelContext=new TravelContext(); travelContext.setStrategy(new PlaneStrategy()); travelContext.travel(); travelContext.setStrategy(new WalkStrategy()); travelContext.travel(); travelContext.setStrategy(new SubwayStrategy()); travelContext.travel(); } }
Examples of common android policy modes:
Rule mode example: ListAdapter
When changing the specific implementation of the Adapter, The ListView. setAdapter (…) is still called (...) Method, view the ListView source code, and find that the parameter of the setAdapter method isListAdapter:
The ListAdapter isInterface, ArrayAdapter and BaseAdapter are an implementation class.
Example 2: TimeInterpolator