As the beginning. It is necessary to explain. Writing an article is not forced by me. It is just a record. First of all, let's define the policy mode! Policy mode: defines algorithm clusters and encapsulates them separately. They can be exchanged. In this way, we can make the algorithm changes independent of the algorithm client!
Here is an example of a duck. A duck has many behaviors, such as calling and flying, but different types of ducks have different behaviors. Therefore, the following methods may be used:
"All ducks can swim! "" Quack "" fly"
- The following code overwrites a specific instance:
WoodDuck "" "wood duck won't"
- However, the result is that inheritance is used for the purpose of reuse, but the effect is not good. As a result, not all subclasses have superclasses, and the code is repeated in more subclasses, it is also difficult to know the full behavior of all ducks. The behavior during running is not easy to change. Changing One will lead to changes that other ducks don't want!
- Here, you may think of separating fly and quack from the super class, defining the interfaces of flyable and quackable, and implementing them in sub-classes. Although such an approach can solve some of the problems, it is only from a nightmare to another nightmare. Think about it. java is a single inheritance. If it is inside a flying duck, there are other changes in flight movements. Will it cause code to become reusable? If there are many sub-classes, isn't it very troublesome to modify the flight or calling behavior of so many sub-classes?
Think about the definition at the beginning. Defining an algorithm family is to extract and encapsulate changeable things!Then we can do the following: first define the fly and quack interfaces, and implement corresponding interfaces for different flight behaviors or shouting behaviors, as long as the implementation class of the behavior is implemented, the code is relatively simple. I will not post it. Design Principles of Rule patterns: Identify potential changes in applications and separate them from those that do not need to be changed. Try to program the interface. Do not implement programming, use combinations, and use less inheritance