Design Pattern _ strategy Pattern
Strategy Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. (Define a set of algorithms, encapsulate each algorithm, and enable exchange between them)
Context: Context Role Strategy: Policy, algorithm family abstraction, usually interface ConcreteStrategy: specific policy role
Public interface Strategy {// algorithm of Rule mode public void doSomething ();}
Public class ConcreteStrategy1 implements Strategy {public void doSomething () {System. out. println (algorithm of Policy 1 );}}
Public class ConcreteStrategy2 implements Strategy {public void doSomething () {System. out. println (algorithm of Policy 2 );}}
Public class Context {// abstract policy private Strategy strategy = null; // The constructor sets the specific policy public Context (Strategy _ strategy) {this. strategy = _ strategy;} // The encapsulated policy method public void doAnythinig () {this. strategy. doSomething ();}}
Test
Public static void main (String [] args) {// declare a specific Strategy strategy = new ConcreteStrategy1 (); // declare the Context object context Context = new Context (Strategy ); // execute the encapsulated method context. doAnythinig ();}
With the object-oriented and polymorphism mechanism, algorithms can be switched freely and have better scalability. The disadvantage is that you must first know which policies are in place to decide which strategy to use. This is against the Demeter law.
This is too simple, so there will be no nonsense.