This is the third blog. In this tutorial, We will design the Food class. This is a key part of the game. It directly determines the scalability and playability of the game...
Enter the subject:
Let's take a look at the class diagrams of the Food class:
We can see that there are a variety of foods with many identical attributes and methods. Therefore, we can easily think of using the inherited Food class.
The new class diagram looks like this:
In this way, when we add a new transaction type to the game, we only need to inherit the Food class and override the draw method. (Different foods have different appearances. Therefore, you need to implement this method by yourself)
But it is worth noting that every food has a variety of sports. For example: horizontal movement, vertical movement, static... If you write these methods in a specific thing class, the first move method will become very complicated, and there will be various branches and judgments in it...
Then, if we upgrade the game later, such as adding a new kind of motion mode or deleting a new kind of motion mode, it will become very cumbersome and will not be conducive to code reuse.
In this case, we need to adopt a design mode: Policy mode.
We Abstract The move method into a class MoveBehaviour.
The new class diagram looks like this:
When we need to add a new motion mode, we only need to write a class to inherit MoveBehavior and implement the specific move method.
This completes the food design. After this design, we can flexibly create new foods and add new sports patterns to them... Amazing !!!
Let's take a look at the project structure: www.2cto.com.
By placing the source code in the corresponding package, it is more conducive to game management.
For the source code, see the final version!
From the EaSy Column