During this period of time, the project encounteredStrategySo I learned about it and made a summary.
StrategyPolicy mode is an object behavior mode. I want to use a word to express its role."Same things".A common goal can be achieved through different behaviors. Mainly to cope with: Some objects useAlgorithmIt may be varied and often changes. If these algorithms are implemented within an object, the object will become very complex and may even cause a performance burden.
GofDesign Patterns: defines a series of algorithms, encapsulates them one by one, and enables them to replace each other. This mode allows algorithms to be independent from their customer changes.
StrategyThe schema structure is as follows:
We can easily see that:StrategyThe Mode actually encapsulates the algorithms one by one.Concretestrategya,Concretestrategyb,ConcretestrategycBut they all inherit from an interface.ContextYou can call a non-algorithm in a multi-state manner.
StrategyThe implementation of the mode is as follows:
Now let's look at a scenario: On my way home from work, I can have these options: walking, cycling, and taking a bus (in different ways, the only purpose is to go home ). First, we need to abstract the algorithm:
Public interface istrategy
{
Void ontheway ();
}
Next, we need several ways to walk, ride, and ride.
Public class implements strategy: istrategy
{
Public void ontheway ()
{
Console. writeline ("walk on the road ");
}
}
Public class ridebickstragtegy: istrategy
{
Public void ontheway ()
{
Console. writeline ("Ride the bicycle on the road ");
}
}
Public class carstragtegy: istrategy
{
Public void ontheway ()
{
Console. writeline ("drive the car on the road ");
}
}
Use the clientCodeCall the encapsulated algorithm interface to implement a walking home scenario:
Class Program
{
Static void main (string [] ARGs)
{
Console. writeline ("arrive to home ");
Istrategy strategy = new strategy Strategy ();
Strategy. ontheway ();
Console. Read ();
}
}
The running result is as follows;
Arrive to home
Walk on the road
To implement other methodsContextChangeIstrategyYou can use the example object.
StrategyKey points of the Mode:
1,StrategyIts subclass provides a series of reusable algorithms for components, so that the types can be easily switched between algorithms as needed during runtime. The so-called encapsulation algorithm supports algorithm changes.
2,StrategyThe mode provides another option other than the condition-based judgment statement. The condition-based judgment statement is eliminated, that is, coupling. Code that contains many condition-based judgment statements usually requiresStrategyMode.
3,StrategyThe mode is algorithm-centric and can beFactory methodFor joint use, the configuration file is used in the factory to dynamically configure the Changed Points. In this way, the changes are put to the runtime.
4, AndTemplate MethodCompared,StrategyThe mode is centered on method encapsulation.