在这一节,我们需要实现在枪械信息上显示弹夹容量

直接在UIContorller上面添加一些代码

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
32
33
34
35
using UnityEngine;
using FrameWorkDesign;
using System;

namespace ShootingEditor2D
{
public class UIController : MonoBehaviour,IController
{
//...

private int m_MaxBulletCount;//

private void Awake()
{
//...

//查询
var mGunConfigModel = this.GetModel<IGunConfigModel>();//
var mGunConfigItem = mGunConfigModel.GetItemByName(m_GunSystem.CurrentGun.Name.Value);//
m_MaxBulletCount = mGunConfigItem.BulletMaxCount;//
}

//..

private void OnGUI()
{
//...
GUI.Label(new Rect(10, 60, 300, 100), $"枪内子弹:{m_GunSystem.CurrentGun.AmmoNumInGun.Value}/{m_MaxBulletCount}",m_LableStyle.Value);//
//...

}
//...

}
}

显示效果,其中的“3/7”说明查询成功

弹夹容量查询

查询逻辑

在这次的逻辑编写时,我们接触到了一些简单的查询逻辑,这个查询是在表现层初始化的时候进行的

1
2
3
var mGunConfigModel = this.GetModel<IGunConfigModel>();//
var mGunConfigItem = mGunConfigModel.GetItemByName(m_GunSystem.CurrentGun.Name.Value);//
m_MaxBulletCount = mGunConfigItem.BulletMaxCount;//

逻辑是“获取IGunConfigModel——通过CurrentGun的Name得到相应的GunConfigItem——从GunConfigItem获取到弹夹容量”

我们在贫血、充血模型实践说明内提到过查询逻辑应该从表现层Controller分离出来,来防止表现层用来查询的代码量越来越多,可以预见的情况是我们在未来加入捡枪、换枪的命令之后,会比较频繁地查询枪械配置信息。

引入Query(查询)

我们在第一季引入Command的时候介绍过CQRS(Command Query Responsibility Seperation),即读写分离原则,Command负责写数据(增删改),而Query用来读数据。

那么一个最简的查询类模型是什么样的呢?我们来举个例子

在Scripts文件夹内新建一个Query文件夹,在其中新建一个MaxBulletCountQuery脚本

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
using FrameWorkDesign;

namespace ShootingEditor2D
{
public class MaxBulletCountQuery : IBelongToArchitecture,ICanGetModel
{
private readonly string m_GunName;

public MaxBulletCountQuery(string gunName)
{
m_GunName = gunName;
}

public int Do()
{
var mGunConfigModel = this.GetModel<IGunConfigModel>();
var mGunConfigItem = mGunConfigModel.GetItemByName(m_GunName);
return mGunConfigItem.BulletMaxCount;
}

public IArchitecture GetArchitecture()
{
return ShootingEditor2D.Interface;
}
}
}

接着我们修改之前的UIContorller里面的查询逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using UnityEngine;
using FrameWorkDesign;
using System;

namespace ShootingEditor2D
{
public class UIController : MonoBehaviour,IController
{
private int m_MaxBulletCount;

private void Awake()
{
//查询
m_MaxBulletCount = new MaxBulletCountQuery(m_GunSystem.CurrentGun.Name.Value).Do();
}
}
}

我们把查询逻辑封装到一个Query对象中,这种方式在服务端中是标准方式,CQRS是服务端常用的设计原则