The strategy mode of design mode what is a policy mode?
The policy pattern defines the algorithm family, which is encapsulated separately so that they can be replaced with each other, and this pattern allows the algorithm to change without affecting the client using the algorithm.
Uml
This pattern is explained in detail by the following code.
First define the common interface of all supported algorithms, strategy interface
Package strategy; Public Interface Strategy { void algorithminterface ();}
The next definition encapsulates the specific algorithm or behavior of the interface implementation class ABC
package strategy; public class Concretestrategya implements strategy {@ Override public void Algorithminterface () { // TODO Auto-gen erated method Stub System.out.println ("A" ); }}
package strategy; public class Concretestrategyb implements strategy {@ Override public void Algorithminterface () { // TODO Auto-gen erated method Stub System.out.println ("B" ); }}
Package strategy; Public class Implements Strategy { @Override publicvoid algorithminterface () { // TODO auto-generated method stub System.out.println ("C");} }
Then define a context, configure it with a specific concretestrategy, and maintain a reference to the Strategy object
Package strategy; Public class Context { strategy strategy; Public Context (Strategy strategy) { // TODO auto-generated constructor stub this. strategy=strategy; } Public void Contextinterface () { strategy.algorithminterface (); }}
And finally, the test class is defined.
Packagestrategy; Public classTest { Public Static voidMain (string[] args) {Context contexta=NewContext (NewConcretestrategya ()); Contexta.contextinterface (); Context CONTEXTB=NewContext (Newconcretestrategyb ()); Contextb.contextinterface (); Context CONTEXTC=NewContext (NewCONCRETESTRATEGYC ()); Contextc.contextinterface (); }}
You done?
Does that feel weird?
At this point the program becomes a very early routine, that is, the client to determine what algorithm to use. So what's the way to transfer judgment?
Combine it with a simple factory model
Transforming the Context class
Packagestrategy; Public classcontextupdate {strategy strategy; Publiccontextupdate (String type) {//TODO auto-generated Constructor stub Switch(type) { CaseA: Strategy=NewConcretestrategya (); Break; CaseB: Strategy=NewConcretestrategyb (); Break; default: Strategy=NewCONCRETESTRATEGYC (); Break; } } Public voidConcretestrategy () {strategy.algorithminterface (); }}
At this point, the judgment is transferred from the client.
Beginner "design Mode"
Strategy Mode of design pattern