Overview
Define a series of algorithms, encapsulate them one by one, and make them replaceable. This mode allows algorithms to change independently of customers who use it.
Applicability
1. Many related classes only have different behaviors. "Policy" provides a method to configure a class with one of multiple actions. 2. Different variants of an algorithm are required. 3. algorithms use data that customers should not know. Policy modes can be used to avoid exposing complex algorithm-related data structures. 4. A class defines multiple behaviors, and these behaviors appear in the form of multiple condition statements in the operations of this class. Move related condition branches into their respective strategy classes to replace these condition statements.
Participants
1. Strategy defines the public interfaces of all supported algorithms. Context uses this interface to call a concretestrategy-defined algorithm. 2. concretestrategy implements a specific algorithm using the strategy interface. 3. context is configured with a concretestrategy object. Maintain a reference to the strategy object. You can define an interface to allow stategy to access its data.
Class Diagram
Example
Package COM. sql9.actioned;/*** policy mode example, using database backup as an example * @ author iihero */abstract class Strategy {public abstract void backupdatabase ();} class strategyimpla extends Strategy {@ override public void backupdatabase () {system. out. println ("policy 1: full physical backup") ;}} class strategyimplb extends strategy {@ override public void backupdatabase () {system. out. println ("policy 2: Basic online backup") ;}} class strategyimplc extends strategy {@ override public void backupdatabase () {system. out. println ("Policy 3: Incremental online backup") ;}} class dbcontext {strategy Strategy; Public dbcontext (strategy Strategy) {This. strategy = strategy;} public void executebackupdatabase () {strategy. backupdatabase () ;}} public class strategytest {public static void main (string [] ARGs) {system. out. println ("retry policy a"); dbcontext context = new dbcontext (New strategyimpla (); context.exe cutebackupdatabase (); system. out. println ("========================"); system. out. println ("retry policy B"); Context = new dbcontext (New strategyimplb (); context.exe cutebackupdatabase (); system. out. println ("========================"); system. out. println ("retry policy C"); Context = new dbcontext (New strategyimplc (); context.exe cutebackupdatabase ();}}Result
Try policy a policy 1: full physical backup ========================= try policy B policy 2: basic online backup ============================ try policy C 3: Incremental online backup