Use
Policy mode (strategy) It 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.
The policy pattern is a behavioral pattern .
structure
Figure-Strategy mode structure diagram
Strategy: Defines the public interface (ALGORITHMINTERFACE) for all algorithms. The context uses this interface to invoke the specific algorithm defined by Concretestrategy.AbstractclassStrategy {
PublicAbstractvoidAlgorithminterface ();
}
Concretestrategy : Implements the Algorithm interface (ALGORITHMINTERFACE) in the strategy.
classConcretestrategyaextendsStrategy {
@Override
PublicvoidAlgorithminterface () {
SYSTEM.OUT.PRINTLN ("algorithm a");
}
}
classConcretestrategybextendsStrategy {
@Override
PublicvoidAlgorithminterface () {
SYSTEM.OUT.PRINTLN ("algorithm B");
}
}
classConcretestrategycextendsStrategy {
@Override
PublicvoidAlgorithminterface () {
SYSTEM.OUT.PRINTLN ("Algorithm C");
}
}
Context : Configured with a concretestrategy. Maintains a reference to the Strategy object.
classContext {
Strategy strategy;
PublicContext (Strategy strategy) {
This. strategy = strategy;
}
PublicvoidContextinterface () {
Strategy. Algorithminterface ();
}
}
Test code
Public classStrategypattern {
PublicStaticvoidMain (string[] args) {
Context Context1 =NewContext (NewConcretestrategya ());
Context1. Contextinterface ();
Context context2 =NewContext (NewConcretestrategyb ());
Context2. Contextinterface ();
Context CONTEXT3 =NewContext (NewCONCRETESTRATEGYC ());
Context3. Contextinterface ();
}
}View Code
Run results
Algorithm A
Algorithm B
Algorithm CView Code
JAVA design mode policy mode