In the Strategy Pattern, the behavior of a class or its algorithm can be changed at runtime. This type of design pattern is a behavioral model.
In policy mode, we create objects that represent various policies and a context object whose behavior changes as the policy object changes. The policy object changes the execution algorithm of the context object.
Intent: Define a series of algorithms, wrap them one by one, and make them interchangeable.
Main solution: In the case of multiple algorithms, the use of if...else is complex and difficult to maintain.
When to use: A system has many, many classes, and what distinguishes them is their direct behavior.
How to solve: Wrap these algorithms into a single class and replace them arbitrarily.
Key code: implements the same interface.
Application example: 1, Zhuge Liang's tricks, each kit is a strategy. 2, the way of travel, choose to ride a bicycle, take a car, each type of travel is a strategy. 3. LayoutManager in JAVA AWT.
Advantages: 1. The algorithm can be switched freely. 2. Avoid using multiple conditional judgments. 3. Good scalability.
Disadvantages: 1. The strategy category will increase. 2. All strategy classes need to be exposed.
Usage scenarios: 1. If there are many classes in a system, the only difference between them is their behavior, then using a policy pattern can dynamically let an object choose a behavior in many behaviors. 2. A system needs to dynamically select one of several algorithms. 3. If an object has a lot of behavior, if you don't use the proper mode, these behaviors have to be implemented using multiple conditional selection statements.
Note: If a system has more than four strategies, you need to consider using a mixed mode to solve the problem of policy class expansion.
We will create an Strategy interface that defines the activity and an entity policy class that implements the Strategy interface. Context is a class that uses a certain strategy.
StrategyPatternDemo, our demo class uses Context and a policy object to demonstrate how the Context changes behavior when the policy it configures or uses changes.
Create an interface.
Create an entity class that implements the interface.
Create the Context class.
Use Context to see behavior changes when it changes the policy Strategy.
Executing the program, outputting results:
10 + 5 = 15 10 - 5 = 5 10 * 5 = 50