首先实现命令模式的基本流程:
需要三个类(命令发起者,具体命令类(继承自抽象命令类),命令执行者),命令执行操作放在命令执行者的类中,具体命令类来决定具体执行的是哪一个或哪些命令执行操作。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CommandModelTest : MonoBehaviour
{
void Start()
{
Receiver myre = new Receiver();
Command mycm = new ConcreCommand(myre);
Invoker invoker = new Invoker(mycm);
invoker.Excute();
}
}
public class Invoker
{
private Command cm;
public Invoker(Command _cm)
{
cm = _cm;
}
public void Excute()
{
cm.Action();
}
}
public abstract class Command
{
protected Receiver rec;
public Command(Receiver _rec)
{
rec = _rec;
}
public abstract void Action();
}
public class ConcreCommand : Command
{
public ConcreCommand(Receiver _rec) : base(_rec)
{
}
public override void Action()
{
rec.fun();
}
}
public class Receiver
{
public void fun()
{
Debug.Log("666");
}
}
下面看看命令模式在unity项目中的具体应用:
首先定义一个抽象命令类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Command
{
public abstract void excute(object param);
}
然后创建核心的命令控制类(命令发起者)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CommandCharge
{
private List<Command> m_listCmds=new List<Command>();
private static CommandCharge mvccharge;
private CommandCharge()
{
}
public static CommandCharge Instance
{
get
{
if (mvccharge == null)
{
mvccharge = new CommandCharge();
}
return mvccharge;
}
}
public void SendCommand<T>(object param) where T : Command, new()
{
Command cm = new T();
m_listCmds.Add(cm);
cm.excute(param);
}
}
然后是具体的命令,如打开窗口关闭窗口等等,从命令基类继承过来,这里我们省略了命令接收者,直接把要执行的操作全部放在具体命令类中。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemCommand : Command
{
public override void excute(object param)
{
Debug.Log(param); //do sth by real need
}
}
最后就可以玩起来了
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour
{
void Start()
{
CommandCharge.Instance.SendCommand<ItemCommand>(666);
}
}
总结:命令模式的要点在于把抽象的命令具体化,所以缺点就是可能会需要很多继承自命令基类的具体类,但是对于一些统一的操作效果很好,还是从打开窗体说起,创建OpenWindowCommand类继承自Command,在excute方法中,形参传对应窗体的名称,如果池子里没有该窗体就Resource.load并实例化出来并加入到池子里,如果池子里有该窗体就直接SetActive(true)就ok了,这样可以打开所有的窗体。