Today to tell you about tian Ji horse racing story. If there are similarities, purely coincidental! In the Warring States Period (475-221 AD), the warring states was divided and the smoke of war was everywhere. After dinner, there were many recreational activities, among which horse racing was the most popular. One day, Sun Bin saw Tian Ji like a dead chicken and knew that he had lost the horse race to the King of Qi. He immediately seized Tian Ji and went to a rematch with the King.

Sun bin: “small ji, brother looked at you distressed, brother out of countermeasures to help you win a dish how?” .

Tian Ji heard after the happy fly, stare big two goldfish eyes “Really? As long as I can win, I will go through fire and water.

Sun bin in the mind ten thousand grass mud horse pentium, almost did not choke dead oneself “roll aside go, we this dish show hand with him!” The race is on and strategy mode is on. Here there should be BGM “let us live with the world is a little guilty ride pentium share the bustling world… Uh-oh, uh-oh, uh-oh.”


I. Strategic mode

define

Define a set of algorithms and encapsulate each one so that they can switch between them.

The characteristics of

1) A set of algorithms, that’s different strategies.

2) This set of algorithms all implement the same interface or inherit the same abstract class, so they can switch with each other.

UML


Policy pattern UML diagram. PNG

There are three roles involved in the policy pattern:

– Encapsulated role: the entry to the upper-level access policy that holds a reference to the abstract policy role.

– Abstract policy role: Provides interfaces or abstract classes that define methods and attributes that must be owned by policy groups.

– Concrete policy role: Implements abstract policies and defines specific algorithm logic.

Second, the actual combat

Before the match with Qi Wei King to analyze the previous lost “strategy”, first look at the encapsulation character, the code is as follows:

public class Context { private Strategy strategy; @param strategy */ public Context(strategy) {this.strategy = strategy; } /** * call policy */ public void contextInterface() {strategy.algorithmLogic(); }}Copy the code

Context holds a reference to the Strategy and provides a method to invoke the Strategy, unambiguously.

Abstract the policy role and define the method of the policy group. The code is as follows:

public interface Strategy {

    public void algorithmLogic();

}
Copy the code

The “strategy” for losing a game is also a strategy, which is a specific strategy role class. Look at the code:

Public class ConcreteStrategyA implements Strategy{@override public void algorithmLogic() { System.out.println(" First race: first horse vs first horse second race: medium horse vs medium horse third race: low horse vs low horse Result: lose!" ); }}Copy the code

See here, Sun Bin a burst of speechless, miserable also have to see the results, the client code is as follows:

Public class Client {public static void main(String[] args) { Context = new Context(New ConcreteStrategyA()); context.contextInterface(); }}Copy the code

Two lines of code, passing in a specific policy object and calling the policy entry method, run the following:

Race 1: superior horse vs superior horse Race 2: Medium horse vs medium horse Race 3: inferior horse vs inferior horse Result: Lose!

Tian Ji said to Sun Bin, “Brother bin, I’m afraid!” Sun bin: “Don’t be afraid, brother in!” .

Tian Ji went to the king, “Your Majesty, let’s… Play again. If you lose, eat.”

Chou Chou Sun bin out of the strategy, a glimpse of the military style, “win” the specific strategy class code is as follows:

Public class ConcreteStrategyB implements Strategy{@override public void algorithmLogic() {// Win System.out.println(" First race: inferior horse vs superior horse second race: Superior horse vs medium horse third race: Inferior horse vs inferior horse result: win!" ); }}Copy the code

Let’s look at the client code:

Public class Client {public static void main(String[] args) { Context Context = new Context(new ConcreteStrategyB()); context.contextInterface(); }}Copy the code

The running results are as follows:

Race 1: inferior horse vs superior horse Race 2: Superior horse vs inferior horse Race 3: Inferior horse vs inferior horse result: Win!

Tian Ji beat rotten palm, it is important that today’s dinner has landed, but also to bin brother to the body of……

Advantages and disadvantages of strategic mode

advantages

1) Good scalability. Add a policy that simply implements the interface and writes concrete logic. When the old strategy is no longer needed, simply eliminate it.

2) Good encapsulation. The entry to the policy is encapsulated in the Context wrapper class, and the client just needs to know which policy to use and which policy object to pass.

3) Avoid multiple conditional judgments like simple factory model.

disadvantages

1) The client must understand each policy of the policy group and decide which policy to use, that is, each policy must be exposed to the client.

2) If there are more policies, the number of policy classes will increase.

Four, extension,

One drawback of the policy mode is that all policies must be exposed and the client can choose the policy to use. Now to fix this defect, which needs to be combined with the simple factory pattern, read on.

Of course, military strategist Sun Bin will also think of this point, how may their routines all exposed to others, that is how to play. However, history did not say that Sun Bin improved this, now it is I to improve this defect, ha ha ha ~

Strategy factory

If you think about a problem, the policy is exposed, the improvement is to hide the policy, and factory mode has this effect, the client doesn’t need to know what the policy is, just the result. OK, so can we use factory mode to generate policies as products? The answer is yes. The entry point to the policy pattern is in the Context wrapper class, which can be manipulated from this role. First look at the code:

public class Context { private Strategy strategy; // Put the create policy in the wrapper role, Public void Factory (String strategyType) {if (strategyType.equals("WIN")) {strategy = new ConcreteStrategyB(); } else if (strategyType.equals("LOSE")) { strategy = new ConcreteStrategyA(); }} /** * algorithtInterface () {strategy.algorithmLogic(); }}Copy the code

The code is simple, adding a factory method that creates a policy object. In this way, the client does not need to understand the specific policy, but only the results of the specific policy. Take a look at the client code:

public class Client { public static void main(String[] args) { Context context = new Context(); context.factory("LOSE"); context.contextInterface(); }}Copy the code

conclusion

Note the difference between the policy pattern and the factory method pattern, which was described in the factory method pattern and will not be explained here. Strategy mode itself is relatively simple, focus on its expansion and the comparison of other modes, analysis of their advantages and disadvantages. Is there a downside to the strategy factory model? Obviously, if a policy needs to be added or removed, the Context must be modified, which does not comply with the open closed principle. In “Zen of Design Patterns”, it is proposed to improve the strategy pattern through policy enumeration and reflection mechanism, which is admired. However, to add or remove policies, you still have to modify the enumeration, which also does not match the open and closed principle. According to the situation of your own project, choose the most suitable model for your project. Next up, chain of responsibility, goodbye!

Design pattern making Java source code download: https://github.com/jetLee92/DesignPattern