介绍
| 定义 | 案例 | 问题堆积在哪里 | 解决办法 |
| 行为形设计模式
| 发布命令 1 打印1-9 a 打印A-G | 如果有更多的命令 命令处理方式更加多样性 更复杂 处理命令的顺序 | 拆分角色:降低耦合度 命令类(一个命令一个类) 具体接收类(具体的处理命令 当前 用静态方法代替) 执行执行 ( 先进先执行 新进后执行 优先等级高的先执行 )可以设置多种优先等级 |
1 . 一个命令接口类
2 “命令接口类” 包含了 “处理类”
3 传给了“调用方” 来定义如何调用

角色1 BaseCommand :抽象命令
角色2.1 Command1 :具体命令1
角色2.2 CommandA :具体命令2
角色3 Receiver:具体命令处理
角色4 Invoke:执行方
-
- public abstract class BaseCommand
- {
- // 委托:命令
- public delegate void ExecuteCommand();
- public ExecuteCommand executeCommand = null;
-
- public BaseCommand(ExecuteCommand executeCommand)
- {
- this.executeCommand += executeCommand;
- }
-
- // 执行命令
- public abstract void Execute();
- }
-
- public class Command1 : BaseCommand
- {
- public Command1(ExecuteCommand executeCommand)
- : base(executeCommand)
- {
-
- }
-
- public override void Execute()
- {
- if (null != executeCommand)
- executeCommand();
- }
- }
-
- public class CommandA : BaseCommand
- {
- public CommandA(ExecuteCommand executeCommand)
- : base(executeCommand)
- {
- }
-
- public override void Execute()
- {
- if (null != executeCommand)
- executeCommand();
- }
- }
- using UnityEngine;
-
- ///
- /// 功能集合
- ///
- public class Receiver
- {
- static public void Show1to9()
- {
- Debug.Log("打印:123456789!");
- }
-
- static public void showAtoG()
- {
- Debug.Log("打印:ABCDEFG!");
- }
- }
- ///
- /// 调用者
- /// 可以继续扩展:
- /// 1 收集命令
- /// 2 命令顺序不同 倒序 或者 特殊优先级高的先执行
- /// 3 扩展为设计模式深入设计
- ///
- public class Invoke
- {
- private BaseCommand commend = null;
-
- Invoke() { }
- public Invoke(BaseCommand commend)
- {
- this.commend = commend;
- }
-
- public void Execute()
- {
- commend.Execute();
- }
- }
- using System;
- using UnityEngine;
-
- public class TestML : MonoBehaviour
- {
- void Start()
- {
- BaseCommand command = null;
- string strCommand = "1";
-
- switch (strCommand)
- {
- case "A":
- command = new CommandA(Receiver.showAtoG);
- break;
-
- case "1":
- command = new Command1(Receiver.Show1to9);
- break;
-
- default:
- break;
- }
-
- // 执行命令
- Invoke invoke = new Invoke(command);
- invoke.Execute();
- }
-
- }

设计模式需要放到框架设计 才更有意义,有时候如果有一个小的需求并且后期也不会改动,直接用流程的方式写代码更加简单,进一步设计反而没必要!
如果放入项目框架, 命令模式的4个角色还能继续细分,细分后再细分,考虑后期的各种变动,根据策划案进一步细分优化,细节处使用更多的设计模式。
一步步优化下去, 推迟细节再推迟。。直到config配置文件或者Execl。