This series mainly records what the design pattern intends to be, what issues it wants to solve, and when it can be used; how it solves it, master its structure diagram, remember its key code; be able to think of at least two of its application instances, one in life and one in software; What are the advantages and disadvantages of this model, and what use scenarios are there, what should I pay attention to when using it.
13. Rule Mode
Intention: Define a series of algorithms, encapsulate them one by one, and make them replaceable.
Main Solution: Complex and difficult to maintain with if. else when multiple algorithms are similar
When to use: A system has many classes, but what distinguishes them is their direct behavior.
Solution: Encapsulate these algorithms into one class and replace them randomly
Structure:
Key code: Implement the same interface
Application Instance: 1. Zhuge Liang's tips. Every tip is a strategy. 2. Travel methods. Choosing to ride a bicycle or take a bus is a strategy. 3. LayoutManager in JAVA AWT
Advantages: 1. algorithms can be switched freely. 2. Multi-condition judgment is avoided. 3. good scalability.
Disadvantages: 1. The number of policies increases. 2. All policies need to be exposed.
Use Cases1. If there are many classes in a system, the only difference between them is their behavior, the policy mode allows an object to dynamically select a behavior among many behaviors. 2. A system must dynamically select one of several algorithms. 3. If an object has many behavior, if you do not need an appropriate pattern, you have to use multiple conditional selection statements to implement these behaviors.
Notes: If a system has more than four policies, you need to consider using the hybrid mode to solve the problem of policy expansion.