Structure |
|
Intention |
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. |
Applicability |
- Many of the related classes are simply behavior-specific. Policy provides a way to configure a class with one behavior in multiple behaviors.
- You need to use different variants of an algorithm. For example, you might define algorithms that reflect different spatial/temporal tradeoffs. When these variants are implemented as a class hierarchy of an algorithm [H O 8 7], the policy mode can be used.
- The algorithm uses data that the customer should not know about. You can use the policy mode to avoid exposing complex, algorithmic-related data structures.
- 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 s t r a t e G y classes in place of these conditional statements.
|
1 usingSystem;2 3 4 Abstract classStrategy5 {6 Abstract Public voiddoalgorithm ();7 }8 9 classFirststrategy:strategyTen { One Override Public voidDoalgorithm () A { -Console.WriteLine ("In first strategy"); - } the } - - classSecondstrategy:strategy - { + Override Public voidDoalgorithm () - { +Console.WriteLine ("In second strategy"); A } at } - - classContext - { - strategy S; - PublicContext (Strategy strat) in { -s =Strat; to } + - Public voidDoWork () the { * //some of the context ' s own code goes here $ }Panax Notoginseng - Public voiddostrategywork () the { + //Now we can hand off to the strategy to do some A // More work the s.doalgorithm (); + } - } $ $ /// <summary> - ///Summary description for Client. - /// </summary> the Public classClient - {Wuyi Public Static intMain (string[] args) the { -Firststrategy Firststrategy =Newfirststrategy (); WuContext C =NewContext (firststrategy); - c.dowork (); About c.dostrategywork (); $ - return 0; - } -}
Policy Mode
The strategy mode of behavioral design pattern