深圳企业社保网站官网,百度制作企业网站多少钱,做自媒体资源的网站,湖南网站建设哪里好命令模式 介绍
定义案例问题堆积在哪里解决办法 行为形设计模式 就是把 “发布命令 执行命令”细化为多个角色 每个角色又能继续细化 发布命令 1 打印1-9 a 打印A-G 如果有更多的命令 命令处理方式更加多样性 更复杂 处理命令的顺序拆分角色#xff1a;降低耦合度 命令类降低耦合度 命令类一个命令一个类 具体接收类具体的处理命令 当前 用静态方法代替 执行执行 先进先执行 新进后执行 优先等级高的先执行 可以设置多种优先等级
类图
1 . 一个命令接口类
2 “命令接口类” 包含了 “处理类”
3 传给了“调用方” 来定义如何调用 代码
角色1 BaseCommand 抽象命令
角色2.1 Command1 具体命令1
角色2.2 CommandA 具体命令2
角色3 Receiver具体命令处理
角色4 Invoke执行方
BaseCommand public abstract class BaseCommand
{// 委托命令public delegate void ExecuteCommand();public ExecuteCommand executeCommand null;public BaseCommand(ExecuteCommand executeCommand){this.executeCommand executeCommand;}// 执行命令public abstract void Execute();
}Command1 public class Command1 : BaseCommand
{public Command1(ExecuteCommand executeCommand): base(executeCommand){}public override void Execute(){if (null ! executeCommand)executeCommand();}
}CommandA public class CommandA : BaseCommand
{public CommandA(ExecuteCommand executeCommand): base(executeCommand){}public override void Execute(){if (null ! executeCommand)executeCommand();}
}Receiver
using UnityEngine;/// summary
/// 功能集合
/// /summary
public class Receiver
{static public void Show1to9(){Debug.Log(打印123456789);}static public void showAtoG(){Debug.Log(打印ABCDEFG);}
} Invoke
/// summary
/// 调用者
/// 可以继续扩展
/// 1 收集命令
/// 2 命令顺序不同 倒序 或者 特殊优先级高的先执行
/// 3 扩展为设计模式深入设计
/// /summary
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。