从这一节开始,着手实践贫血模型和充血模型这两个概念,一上来就用纸上设计去实践充血模型非常困难,因为纸上设计需要有一定的抽象能力,而这个抽象能力的前提是大量的编码实践。所以我们先进行一些充血模型的编码实践。
首先看一下开枪功能实现图

功能实现图转化成代码的方法,有两种简单的方式:
- 从表现层开始写起。先实现界面布局,然后界面基本元素实现,然后再写一个Command(比如ShootCommand),再接着写Command对应的System,比如IGunSystem等,以此类推,就是按照:表现层——交互逻辑——数据/系统——表现逻辑 这样的顺序去实现功能。
- 从数据开始写起。先设计数据结构,再实现表现层的内容,这种方式的好处是一开始可能考虑得比较周全,程序结构不容易混乱,但是对设计者要求比较高,需要有一定得编码积累和设计经验。
第一种方式简单,符合常人思维,配合纸上设计,也能达到尽可能得周全。
GunInfo重构
修改GunInfo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| using FrameWorkDesign; using System;
namespace ShootingEditor2D { public enum GunState { Idle, Shooting, Reload, EmptyBullet, CoolDown } public class GunInfo { [Obsolete("请使用 AmmoNumInGun",false)] public BindableProperty<int> AmmoNum { get => AmmoNumInGun; set => AmmoNumInGun = value; }
public BindableProperty<int> AmmoNumInGun;
public BindableProperty<string> Name;
public BindableProperty<GunState> State;
public BindableProperty<int> BulletCountOutGun; } }
|
在团队协作中,为属性和字段重命名是非常慎重的,所以这里演示使用Obsolete特性标记的方式,这样在Unity控制台或一些IDE中都会出现警告。
接下来根据IDE中标注的引用数量,将其中的AmmoNum
替换为AmmoNumInGun
即可,在这里不作演示,修改完后删掉AmmoNum
这一部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| using FrameWorkDesign;
namespace ShootingEditor2D { public enum GunState { Idle, Shooting, Reload, EmptyBullet, CoolDown } public class GunInfo {
public BindableProperty<int> AmmoNumInGun;
public BindableProperty<string> Name;
public BindableProperty<GunState> State;
public BindableProperty<int> BulletCountOutGun; } }
|
BindableProperty
不支持枚举,我们删除掉里面的泛型约束
修改BindableProperty
的代码,删除掉里面的where T : IEquatable<T>
约束
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| using System;
namespace FrameWorkDesign { public class BindableProperty<T> {
public class BindablePropertyUnregister<T> : IUnregister { } } }
|