【命令模式】個人理解就是一種單純的解耦吧,把原本的像switch case,if else這種拆分開了,方便擴展和維護。
貼代碼:
using UnityEngine;
/// <summary>
/// 設計模式——命令模式
/// </summary>
public class DesignMode_Command : MonoBehaviour {
// Use this for initialization
void Start () {
Leader leader = new Leader();
ITMonkey monkey = new ITMonkey();
DoCommand dc = new DoCommand();
leader.ReleaseCommand(dc,monkey);
AddCommand ac = new AddCommand();
leader.ReleaseCommand(ac, monkey);
CancleCommand cc = new CancleCommand();
leader.ReleaseCommand(cc, monkey);
}
}
/// <summary>
/// 命令基類
/// </summary>
public abstract class Command
{
public abstract void SetCommand();
public abstract void Excute(ITMonkey monkey);
}
public class DoCommand : Command
{
public override void Excute(ITMonkey monkey)
{
monkey.Action();
}
public override void SetCommand()
{
Debug.Log("來活了");
}
}
public class AddCommand : Command
{
public override void Excute(ITMonkey monkey)
{
monkey.Action();
}
public override void SetCommand()
{
Debug.Log("把這個需求加上");
}
}
public class CancleCommand : Command
{
public override void Excute(ITMonkey monkey)
{
monkey.Action();
}
public override void SetCommand()
{
Debug.Log("撤銷命令");
}
}
public class Leader
{
public Command mCommand;
public ITMonkey mMonkey;
/// <summary>
/// 下達命令
/// </summary>
/// <param name="command"></param>
public void ReleaseCommand(Command command,ITMonkey monkey)
{
command.SetCommand();
command.Excute(monkey);
}
}
/// <summary>
/// 程序員
/// </summary>
public class ITMonkey
{
/// <summary>
/// 執行命令
/// </summary>
public void Action()
{
Debug.Log(string.Format("加班敲代碼......"));
}
}
其實程序員類裏面應該有多個Action的,根據傳過來的命令不同做出不同的反應,但是我一想,能做出的反應除了改代碼、寫代碼好像也沒啥其他行爲~(皮這一下,我很開心)。