: This article focuses on getting started with the design mode-policy mode (php version). If you are interested in the PHP Tutorial, please refer to it. Scenario: A game that simulates ducks. There are various ducks in the game, which can be called and swimming.
The diagram of the preliminary design scheme is shown in the following uml class diagram:
Change: It looks impeccable in the early stage until one day the game needs to fly. the simplest solution is to add a fly method to the parent class. the uml diagram is as follows:
One day the disaster happened: there were a lot of rubber ducks flying around ....
The simplest solution is to overwrite the fly method in the RubberDuck class. the class diagram is as follows:
Change: The game is becoming more and more popular. in addition to the rubber duck, there are also a variety of ducks, such as DecoyDuck (bait duck), which can neither be called Nor fly, should we overwrite the fly and quack methods for each class?
Solution:
1. design fly and quack as interfaces. only the Flying Duck will be inherited. the corresponding uml class diagram is as follows: (incorrect, swim method is not required in decoyduck)
Disadvantages: this solution is prone to code duplication and does not reuse the same fly and quack methods.
2. make flyable and quackable into an independent class as duck attributes. the corresponding uml class diagram is as follows:
In this method, redheadduck, rubberduck, mallardduck, and decoyduck respectively use the related methods in the flyablity and quackablity classes to implement specific fly and quack methods. This scheme violates the principle of "programming for interfaces rather than specific implementations" in the design philosophy, and cannot ensure that the functions required by various ducks exist in the flyablity and quackablity classes.
3. design flyable and quackable as interfaces. the specific implementation is completed by various flight and call skills.
The Uml class diagram is as follows:
Of course, the situation is still changing. it does not mean that the rubber duck cannot fly now. we need a way to set its flight capabilities, as shown in the following figure:
Download the code: download the code (http://www.walk-sing.com/strategystrategy.zip)
Note: In the actual code writing process, it is found that the quack method is also the quack construction method on the mobile phone when the quack method is used after the quackable is implemented, so I changed the quack class name to the quacking class during writing.
The above introduces the design mode entry-policy mode (php version), including some content, hope to be helpful to friends who are interested in PHP tutorials.