The policy pattern defines a series of algorithms, encapsulates each algorithm, and allows them to be replaced with each other, allowing the algorithm to be independent of the client using it, and the application scenario, such as third-party payment algorithms for docking different banks.
IMPORTANT: 1) abstract policy roles
2) Specific policy roles: packaging-related algorithms and behaviors
3) Environment role: holds a reference to a policy class that is eventually called to the client
1. Abstract Policy Interface
Public Interface Swimmingstratege { publicvoid swimming ();}
2. Specific strategy role Swimmingwithfoot
Public class Implements Swimmingstratege { publicvoid swimming () { System.out.println (" I slide through the water with my Feet ");} }
3. Specific strategy role Swimmingwithwind
Public class Implements Swimmingstratege { publicvoid swimming () { System.out.println ( "I use the wind to swim in the water");} }
4. Environmental role Duck Abstract class
Public Abstract classDuck { Public voidQuack () {System.out.println ("Quack"); } Public Abstract voiddisplay (); PrivateSwimmingstratege Swimmingstratege; Public voidSetswimmingstratege (Swimmingstratege swimmingstratege) { This. Swimmingstratege =Swimmingstratege; } Public voidswimming () {swimmingstratege.swimming (); }}
5. Environmental role Realduck
Public classRealduckextendsDuck { PublicRealduck () {Super(); Super. Setswimmingstratege (Newswimmingwithfoot ()); } @Override Public voidQuack () {Super. Quack (); } Public voiddisplay () {System.out.println ("I'm a real duck."); }}
6. Environmental role
Public classYellowduckextendsDuck { PublicYellowduck () {Super(); Super. Setswimmingstratege (NewSwimmingwithwind ()); } @Override Public voidQuack () {Super. Quack (); } Public voiddisplay () {System.out.println ("I'm a rhubarb duck."); }}
7. Testing
Public class Model { publicstaticvoid main (string[] args) { new Realduck (); // Duck Duck = new Yellowduck (); Duck.display (); Duck.quack (); Duck.swimming (); }}
Java design mode (vi) policy mode