今天讲一讲设计模式当中的命令模式。
命令模式,其实就是将命令封装成一个对象。
举个例子,现在有一个物体处于原点,我要让他移动到坐标为(1,1,1)的位置。
那么我将她写成一条命令。代码如下:
public class MoveToPos
{
public void Excute(Transform transform)
{
transform.position = new Vector3(1, 1, 1);
}
}
然后我们在场景中创建一个物体,将其坐标设置为原点
创建一个测试脚本挂载到该物体上,并写上调试代码:
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
new MoveToPos().Excute(transform);
}
}
}
当我们按下E键的时候,创建一条移动至(1,1,1)位置的命令并执行。
然后我们运行,并按下E键会发现
确实移动了。
那么问题来了,这么写跟我们直接写一个方法有区别吗?为什么要封装成一个对象呢?
就当前这么看,确实是一样的效果。但是既然是一个对象了,那么我们就可以对他进行扩展。举个例子,我们可以添加一个撤销的方法。
public class MoveToPos
{
Transform transform;
Vector3 lastPos;
public void Excute(Transform transform)
{
lastPos = transform.position;
this.transform = transform;
transform.position = new Vector3(1, 1, 1);
}
public void Cancel()
{
transform.position = lastPos;
}
}
当执行命令时记录一下自身当前的位置并保存引用。
那么我们的测试代码就要改成。
public class Test : MonoBehaviour
{
MoveToPos command;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
command = new MoveToPos();
command.Excute(transform);
}
if (Input.GetKeyDown(KeyCode.C))
{
if (command != null)
command.Cancel();
}
}
}
代码很简单,当按下C键时撤销上次操作。
接着我们在游戏中运行起来,并按下E键,然后按下C键,会发现物体回到了原点。
这个撤销功能也是命令模式的一大特色。将命令封装成对象,可以让我们对操作进行管理,当然并不是说方法就不可以管理,因为C#当中是支持闭包的,我们直接对委托进行管理也是可以的,但是思想却是跟命令模式一样的。
希望对大家有所帮助。