Policy mode:
1 Policy Mode2 Overview3 define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be independent of the customers who use it. 4 5 Applicability61many of the related classes are simply behavior-specific. Policy provides a way to configure a class with one behavior in multiple behaviors. 7 82. You need to use different variants of an algorithm. 9 Ten3the algorithm uses data that the customer should not know about. You can use the policy mode to avoid exposing complex, algorithmic-related data structures. One A4. A class defines a variety of behaviors, and these behaviors appear as multiple conditional statements in the operation of this class. - The related conditional branches are moved into their respective strategy classes in place of these conditional statements. - the - participants -1. Strategy - defines the public interface for all supported algorithms. The context uses this interface to invoke an algorithm defined by a concretestrategy.
+ -2. Concretestrategy + a specific algorithm is implemented with strategy interface. A at3. Context - configured with a Concretestrategy object. - maintains a reference to the Strategy object. -You can define an interface to let stategy access its data.
Test class:
1 Public classTest {2 3 Public Static voidMain (string[] args) {4Context CTX =NewContext (NewStrategyimpla ());5 Ctx.domethod ();6 7CTX =NewContext (NewSTRATEGYIMPLB ());8 Ctx.domethod ();9 TenCTX =NewContext (NewSTRATEGYIMPLC ()); One Ctx.domethod (); A } -}
1 Public classContext {2 3 strategy stra;4 5 PublicContext (Strategy stra) {6 This. Stra =Stra;7 }8 9 Public voidDomethod () {Ten Stra.method (); One } A}
1 Public Abstract class Strategy {23 Public Abstract void method (); 4 }
1 Public class extends Strategy {23 Public void method () {4 System.out.println ("This is the first implementation"); 5 }6 }
1 Public class extends Strategy {23 Public void method () {4 System.out.println ("This is a second implementation"); 5 }6 }
1 Public class extends Strategy {23 Public void method () {4 System.out.println ("This is a third implementation"); 5 }6 }
The great God wrote the code is not the same
Java design pattern--Behavioral mode--strategy mode