First, we have a general understanding of the policy mode.
Intention: Define a seriesAlgorithm, Encapsulate them one by one, and make them replace each other. This mode allows algorithms to change independently of customers who use it.
Structure:
The following describes the design of the duck simulator.
The company needs to design a duck simulator system. The first requirement of the system is: Duck can play with water; duck can scream. The system is designed as follows:
This design mainly uses the parent duck and child green duck and red duck. This design aims to achieveCode.
After a while, the company hopes that the system can meet new requirements: some ducks will fly. Therefore, the system needs to be modified. The modified system may be as follows:
The system adds the "Fly ()" method to the parent class (this method is used to achieve code reuse in the parent class ). Here there are two problems:
(1) All ducks will fly.
(2) the sounds of all ducks are the same.
Note: These two problems can be solved by overwriting the method in the subclass, but this is not a good solution. The more duck categories, the more obvious the disadvantages of this kind of processing.
In fact, the changes in this system are the sounds of ducks and the flying capabilities of ducks. Therefore, we can easily think of making the sounds of ducks and the flying capabilities of ducks into interfaces, encapsulate these changes so that the above two problems can be solved, so the system may be changed to the following:
Mallardduck and redheadduck can both fly and call, rubberduck can only call not fly, decoyduck can not fly or call. It should be said that there is no problem with this system. On the surface, this design fully meets the needs and fully complies with the object-oriented concept. However, when there are many duck categories, you will find that this design lacks code reuse. These two independent interfaces do not seem to make any sense and cannot reduce the workload. It is not as good as the original design. So you may think that the key to the problem is that the methods in the interface are not implemented. What should we do?
Our approach is to make interfaces into classes and use a combination of methods to achieve requirements. Considering the design principle of "interface programming, rather than implementing programming", our system may be designed into the following structure, which is to apply the "Policy" mode.
Source codeDownload:/Files/wxj1020/minisimuduck.rar