Life Cases
For dating with different types of MM, different strategies should be used. For some, it is better to take a movie, for others, it is better to eat snacks, and for some, it is best to go to the beach for romance, the single goal is to get the attention of mm. The key is to catch up with a lot of strategy in the mm tip.
Motivation in Computer
During the software building process, some objects may use a variety of algorithms, which may change frequently. If these algorithms are all encoded into objects, the objects will become very complex; in addition, sometimes unsupported algorithms are also a performance burden.
How can I transparently change the object algorithm at runtime as needed? Decoupling algorithms from objects to avoid the above problems?
Concept
The policy mode defines the algorithm family and encapsulates them separately so that they can be replaced with each other. This mode changes the algorithm and does not affect the customers who use the algorithm. ---- Design Pattern gof
Figure
Code
Strategy class, which defines public interfaces of all supported algorithms
// Abstract algorithm class abstract class Strategy {// algorithm method public abstract void algorithminteface ();}
Concretestrategy encapsulates specific algorithms or actions, inherited from strategy
// Specific algorithm Aclass concretestrategya: Strategy {// algorithm a implementation method public override void algorithminteface () {console. writeline ("algorithm A Implementation"); }}// detailed algorithm bclass concretestrategyb: Strategy {// algorithm B Implementation Method public override void algorithminteface () {console. writeline ("algorithm B Implementation"); }}// the cClass concretestrategyc: Strategy {// algorithm C implementation method public override void algorithminteface () {console. writeline ("algorithm C Implementation ");}}
Use a concretestrategy to configure and maintain a reference to the strategy object.
// Context class context {strategy Strategy; public context (strategy Strategy) {This. strategy = strategy;} // context interface public void contextinterface () {strategy. algorithminteface ();}}
Client code
static void Main(string[] args){ Context context; context = new Context(new ConcreteStrategyA()); context.ContextInterface(); context = new Context(new ConcreteStrategyB()); context.ContextInterface(); context = new Context(new ConcreteStrategyC()); context.ContextInterface(); Console.Read();}
Advantages and disadvantages
Advantages
It provides an alternative to inheritance, and maintains the advantages of inheritance (code reuse) and is more flexible than inheritance (algorithms are independent and can be expanded at will ).
Avoid using multiple conditional transfer statements in the program to make the system more flexible and easy to expand.
Disadvantages
Because each specific policy class generates a new class, the number of classes to be maintained by the system is increased.
Solution:Factory method