找回密码
 立即注册
首页 业界区 科技 游戏编程模式(28种编程模式)

游戏编程模式(28种编程模式)

水苯 昨天 10:48
命令模式

***将命令封装,与目标行为解耦,使命令由流程概念变为对象数据
既然命令变成了数据,就是可以被传递、存储、重复利用的
命令模式(Command Pattern)是一种行为设计模式,它将一个请求封装为一个对象,从而允许用户使用不同的请求、队列或日志请求来参数化其他对象。命令模式也支持可撤销的操作
***应用场景

  • 如果需要通过操作来参数化对象, 可使用命令模式。
  • 如果想要将操作放入队列中、 操作的执行或者远程执行操作, 可使用命令模式。
  • 如果想要实现操作回滚功能, 可使用命令模式。
***实现方式

  • Command:定义命令的接口,声明执行操作的方法。
  • ConcreteCommand:Command 接口的实现对象,它对应于具体的行为和接收者的绑定。
  • Client:创建具体的命令对象,并且设置它的接收者。
  • Invoker:要求命令对象执行请求。
  • Receiver:知道如何实施与执行一个请求相关的操作。
***优点

  • 控制请求处理的顺序:你可以控制请求处理的顺序。
  • 单一职责原则:你可对发起操作和执行操作的类进行解耦。
  • 开闭原则:你可以在不更改现有代码的情况下在程序中新增处理者
将一个请求封装为一个对象,从而允许使用不同的请求或队列或日志将客户端参数化,同时支持请求操作的撤销与恢复
命令就是一个对象化(实例化)的方法调用,封装在一个对象中的方法调用
可以理解命令是面向对象化的回调
  1. // Avatar类继承自MonoBehaviour,这是一个操作者类,负责处理对象的移动。
  2. public class Avatar : MonoBehaviour {
  3.     private Transform mTransform;
  4.     void Start () {
  5.         mTransform = transform;
  6.     }
  7.     public void Move(Vector3 DeltaV3)
  8.     {
  9.         // 使用Transform的Translate方法实现位移。
  10.         mTransform.Translate(DeltaV3);
  11.     }
  12. }
  13. // Command类是一个抽象基类,定义了命令的接口。
  14. public abstract class Command {
  15.     protected float _TheTime;  // 命令对应的时间戳。
  16.     public float TheTime
  17.     {
  18.         get { return _TheTime; }
  19.     }
  20.     public virtual void execute(Avatar avatar) { }
  21.     public virtual void undo(Avatar avatar) { }
  22. }
  23. // CommandMove类继承自Command类,实现了具体的移动命令
  24. public class CommandMove : Command {
  25.     private Vector3 TransPos;
  26.     // 构造函数,接收移动位置和命令执行的时间。
  27.     public CommandMove(Vector3 transPos, float time)
  28.     {
  29.         TransPos = transPos;  // 初始化移动目标位置。
  30.         _TheTime = time;  // 初始化时间。
  31.     }
  32.     // 实现执行命令的方法。
  33.     public override void execute(Avatar avatar)
  34.     {
  35.         // 调用Avatar的Move方法实现移动。
  36.         avatar.Move(TransPos);
  37.     }
  38.     // 实现撤销命令的方法。
  39.     public override void undo(Avatar avatar)
  40.     {
  41.         // 调用Avatar的Move方法,使用相反的向量实现撤销移动。
  42.         avatar.Move(-TransPos);
  43.     }
  44. }
  45. // CommandManager类负责管理和调用命令
  46. public class CommandManager : MonoBehaviour
  47. {
  48.     public Avatar TheAvatar;  // 对Avatar对象的引用。
  49.     private Stack<Command> mCommandStack;  // 用于存储命令的堆栈。
  50.     private float mCallBackTime;  // 记录命令执行的累计时间。
  51.     public bool IsRun = true;  // 标志变量,决定是否运行命令或撤销操作。
  52.     void Start()
  53.     {
  54.         // 初始化命令堆栈和时间。
  55.         mCommandStack = new Stack<Command>();
  56.         mCallBackTime = 0;
  57.     }
  58.     void Update()
  59.     {
  60.         // 根据IsRun变量选择执行命令或运行撤销。
  61.         if (IsRun)
  62.         {
  63.             Control();  // 执行命令控制。
  64.         }
  65.         else
  66.         {
  67.             RunCallBack();  // 执行撤销操作。
  68.         }
  69.     }
  70.      private void Control()
  71.     {
  72.         // 增加命令执行时间。
  73.         mCallBackTime += Time.deltaTime;
  74.         // 获取当前输入的命令对象。
  75.         Command cmd = InputHandler();
  76.         // 如果命令对象不为null,则推入堆栈并执行它。
  77.         if (cmd != null)
  78.         {
  79.             mCommandStack.Push(cmd);
  80.             cmd.execute(TheAvatar);
  81.         }
  82.     }
  83.     private void RunCallBack()
  84.     {
  85.         // 减少当前时间。
  86.         mCallBackTime -= Time.deltaTime;
  87.         // 如果堆栈中存在命令并且当前时间小于堆栈顶部命令的时间,则执行撤销操作。
  88.         if (mCommandStack.Count > 0 && mCallBackTime < mCommandStack.Peek().TheTime)
  89.         {
  90.             // 弹出并撤销顶部命令。
  91.             mCommandStack.Pop().undo(TheAvatar);
  92.         }
  93.     }
  94.     private Command InputHandler()
  95.     {
  96.         // 根据输入生成移动命令。
  97.         if (Input.GetKey(KeyCode.W))
  98.         {
  99.             return new CommandMove(new Vector3(0, Time.deltaTime, 0), mCallBackTime);
  100.         }
  101.         if (Input.GetKey(KeyCode.S))
  102.         {
  103.             return new CommandMove(new Vector3(0, -Time.deltaTime, 0), mCallBackTime);
  104.         }
  105.         if (Input.GetKey(KeyCode.A))
  106.         {
  107.             return new CommandMove(new Vector3(-Time.deltaTime, 0, 0), mCallBackTime);
  108.         }
  109.         if (Input.GetKey(KeyCode.D))
  110.         {
  111.             return new CommandMove(new Vector3(Time.deltaTime, 0, 0), mCallBackTime);
  112.         }
  113.         return null;  // 如果没有按键被检测到,返回null。
  114.     }
  115. }
复制代码
享元模式

***不同的实例共享相同的特性(共性),同时保留自己的特性部分

  • ***传递的信息享元化,可以节约计算时间
  • ***存储的信息享元化,可以节约占用的空间
  • ***所以享元模式可以减少时间与空间上的代价
    享元模式(Flyweight Pattern)是一种结构型设计模式,旨在通过共享对象来尽量减少内存的使用。它通过将重复使用的对象分离成共享和非共享部分,达到复用的目的,从而有效节省内存。享元模式的核心思想是将具有相同内部状态的对象共享,以减少内存占用
***应用场景

  • 当系统中存在大量相似或相同的对象。
  • 对象的创建和销毁成本较高。
  • 对象的状态可以外部化,即对象的部分状态可以独立于对象本身存在。
  • 当需要创建大量相似对象以及共享公共信息的场景,同时也适用于需要考虑性能优化和共享控制的系统。
***实现方式

  • 享元工厂(Flyweight Factory):负责创建和管理享元对象,通常包含一个池(缓存)用于存储和复用已经创建的享元对象。
  • 具体享元(Concrete Flyweight):实现了抽象享元接口,包含了内部状态和外部状态。内部状态是可以被共享的,而外部状态则由客户端传递。
  • 抽象享元(Flyweight):定义了具体享元和非共享享元的接口,通常包含了设置外部状态的方法。
  • 客户端(Client):使用享元工厂获取享元对象,并通过设置外部状态来操作享元对象。客户端通常不需要关心享元对象的具体实现。
***优点

  • 减少内存消耗:通过共享对象,减少了内存中对象的数量。
  • 提高效率:减少了对象创建的时间,提高了系统效率。
***缺点

  • 增加系统复杂度:需要分离内部状态和外部状态,增加了设计和实现的复杂性。
  • 线程安全问题:如果外部状态处理不当,可能会引起线程安全问题
享元模式通过将对象数据切分成两种类型来解决问题。

  • 第一种类型数据是那些不属于单一实例对象并且能够被所有对象共享的数据,例如是树木的几何形状和纹理数据等
  • 其他数据便是外部状态,对于每一个实例它们都是唯一的。例如每棵树的位置、缩放比例和颜色
  1. //随机大小位置渲染
  2. internal class SpecificAttributes  
  3. {  
  4.     public Matrix4x4 TransMatrix;//转换矩阵  
  5.     internal Vector3 mPos;  
  6.     internal Vector3 mScale;  
  7.     internal Quaternion mRot;  
  8.     public SpecificAttributes()  
  9.     {  
  10.         mPos = UnityEngine.Random.insideUnitSphere * 10;  
  11.         mRot = Quaternion.LookRotation(UnityEngine.Random.insideUnitSphere);  
  12.         mScale = Vector3.one * UnityEngine.Random.Range(1, 3);  
  13.         TransMatrix = Matrix4x4.TRS(mPos, mRot, mScale);//基于位置、旋转和缩放创建转换矩阵  
  14.     }  
  15. }
  16. //用于实例化测试用的对象
  17. public class CubeBase : MonoBehaviour  
  18. {  
  19.     private MeshRenderer mMR;  
  20.     private MeshFilter mMF;  
  21.     public Mesh mSharedMesh;  
  22.     public Material mSharedMaterial;  
  23.     private Matrix4x4[] TransInfos;  
  24.   
  25.     private void Start()  
  26.     {  
  27.         Init();  
  28.     }  
  29.     //初始化组件和共享材质和网格  
  30.     public void Init()  
  31.     {  
  32.         mMR = GetComponent<MeshRenderer>();  
  33.         mMF = GetComponent<MeshFilter>();  
  34.   
  35.         if (mMR == null)  
  36.         {  
  37.             Debug.LogError("MeshRenderer component is missing on the GameObject.");  
  38.             return;  
  39.         }  
  40.         if (mMF == null)  
  41.         {  
  42.             Debug.LogError("MeshFilter component is missing on the GameObject.");  
  43.             return;  
  44.         }  
  45.   
  46.         mSharedMaterial = mMR.sharedMaterial;  
  47.         mSharedMesh = mMF.sharedMesh;  
  48.   
  49.         if (mSharedMesh == null)  
  50.         {  
  51.             Debug.LogError("The shared mesh in the MeshFilter is null. Ensure a valid mesh is assigned.");  
  52.         }  
  53.     }  
  54.     //使用Graphics.DrawMeshInstanced方法绘制实例化网格  
  55.     internal void ObjInstancing(int num)  
  56.     {  
  57.         if (mSharedMesh == null)  
  58.         {  
  59.             Debug.LogError("Cannot draw instances because the shared mesh is null.");  
  60.             return;  
  61.         }  
  62.   
  63.         TransInfos = new Matrix4x4[num];  
  64.         for (int i = 0; i < num; i++)  
  65.         {  
  66.             SpecificAttributes sa = new SpecificAttributes();  
  67.             TransInfos[i] = sa.TransMatrix;  
  68.         }  
  69.   
  70.         Graphics.DrawMeshInstanced(mSharedMesh, 0, mSharedMaterial, TransInfos);  
  71.     }  
  72. }
  73. //享元模式控制类
  74. using System.Collections.Generic;  
  75. using UnityEngine;  
  76. using UnityEngine.UI;  
  77.   
  78. public class FlyweightManager : MonoBehaviour  
  79. {  
  80.   
  81.     public GameObject TheObj;  
  82.     public bool IsFlyweight=true;  
  83.     private Text StatusText;  
  84.     private List<Transform> ObjTrs;  
  85.   
  86.     void Start()  
  87.     {  
  88.         ObjTrs = new List<Transform>();  
  89.         StatusText=GameObject.Find("StatusText").GetComponent<Text>();  
  90.         StatusText.text= IsFlyweight?"禁用享元模式":"启用享元模式";  
  91.     }  
  92.   
  93.     void Update()  
  94.     {  
  95.         if (IsFlyweight)  
  96.         {  
  97.             GenerateObjsWithInstancing(1000);  
  98.         }  
  99.         else  
  100.         {  
  101.             GenerateObjsWithoutInstancing(1000);  
  102.         }  
  103.     }  
  104.   
  105.     public void SwitchFlyweight()  
  106.     {  
  107.         IsFlyweight = !IsFlyweight;  
  108.         StatusText.text= IsFlyweight?"禁用享元模式":"启用享元模式";  
  109.     }  
  110.   
  111.     //使用CubeBase脚本的ObjInstancing方法来生成指定数量的实例化对象  
  112.     public void GenerateObjsWithInstancing(int num)  
  113.     {  
  114.         // 遍历 ObjTrs 列表,销毁所有已经存在的游戏对象  
  115.         for (int i = 0; i < ObjTrs.Count; i++)  
  116.         {  
  117.             Destroy(ObjTrs[i].gameObject);  
  118.         }  
  119.         // 清空 ObjTrs 列表,移除所有引用  
  120.         ObjTrs.Clear();  
  121.   
  122.         // 调用 CubeBase 脚本的 ObjInstancing 方法来生成指定数量的实例化对象  
  123.         TheObj.GetComponent<CubeBase>().ObjInstancing(num);  
  124.     }  
  125.     //创建非实例化对象  
  126.     public void GenerateObjsWithoutInstancing(int num)  
  127.     {  
  128.         // 遍历 ObjTrs 列表,销毁所有已经存在的游戏对象  
  129.         for (int i = 0; i < ObjTrs.Count; i++)  
  130.         {  
  131.             Destroy(ObjTrs[i].gameObject);  
  132.         }  
  133.         // 清空 ObjTrs 列表,移除所有引用  
  134.         ObjTrs.Clear();  
  135.   
  136.         // 循环创建指定数量的新游戏对象  
  137.         for (int i = 0; i < num; i++)  
  138.         {  
  139.             // 创建 SpecificAttributes 实例,用于存储新对象的属性  
  140.             SpecificAttributes sa = new SpecificAttributes();  
  141.   
  142.             // 使用 Instantiate 方法创建 TheObj 的副本,并设置其位置和旋转  
  143.             Transform tr = Instantiate(TheObj, sa.mPos, sa.mRot).transform;  
  144.   
  145.             // 设置新对象的材质颜色为白色  
  146.             tr.GetComponent<MeshRenderer>().material.color = Color.white;  
  147.   
  148.             // 设置新对象的局部缩放  
  149.             tr.localScale = sa.mScale;  
  150.   
  151.             // 将新创建的对象的 Transform 添加到 ObjTrs 列表中  
  152.             ObjTrs.Add(tr);  
  153.         }  
  154.     }  
  155. }
复制代码
考虑这么一个需求:
在游戏中,同时有一万个敌人
暂时不考虑渲染压力,单纯设计一个敌人属性的实现
敌人的属性包括

  • 血量
  • 身高
  • 职级有四种:新兵,中士,上士,上尉
  • 血量上限(根据职级不同而变,依次是100,200,500,1000)
  • 移动速度( 根据职级不同而变,依次是 1.0f , 2.0f , 3.0f , 4.0f )
  • 职级对应名字(根据职级不同而变,依次是新兵,中士,上士,上尉)
最原始的做法就是声明一个Attr类,它包含hp,hpMax,mp,mpMax,name
带来的问题是内存浪费,每一个属性对象都同时开辟了hp,hpMax,mp,mpMax,name的内存空间
可以把职级做成枚举,职级对应的属性定义一个字典
  1. public enum AttrType : uint
  2. {
  3.     // 新兵
  4.     Recruit,
  5.     // 中士
  6.     StaffSergeant,
  7.     // 上士
  8.     Sergeant,
  9.     // 上尉
  10.     Captian,
  11. }
  12. public static readonly Dictionary> BaseAttrDict = new Dictionary>
  13. {
  14.     {AttrType.Recruit , new Dictionary<string, float>
  15.     {
  16.         {"MaxHp",100.0f},
  17.         {"MoveSpeed",1.0f},
  18.     }},
  19.     {AttrType.Recruit , new Dictionary<string, float>
  20.     {
  21.         {"MaxHp",200.0f},
  22.         {"MoveSpeed",2.0f},
  23.     }},
  24.     {AttrType.Recruit , new Dictionary<string, float>
  25.     {
  26.         {"MaxHp",500.0f},
  27.         {"MoveSpeed",3.0f},
  28.     }},  {AttrType.Recruit , new Dictionary<string, float>
  29.     {
  30.         {"MaxHp",1000.0f},
  31.         {"MoveSpeed",4.0f},
  32.     }},
  33. };
  34. public float GetMapHp()
  35. {
  36.     return Const.BaseAttrDict[baseAttrType]["MaxHp"];
  37. }
  38. public float GetMoveSpeed()
  39. {
  40.     return Const.BaseAttrDict[baseAttrType]["MoveSpeed"];
  41. }
复制代码
但需求里有一项,要求能访问到职级对应的中文名 为了实现需求,字典的value不能是float,而应该是object
  1. public static readonly Dictionary> BaseAttrDict = new Dictionary>
  2. {
  3.      {AttrType.Recruit , new Dictionary<string, object>
  4.      {
  5.          {"MaxHp",100},
  6.          {"MoveSpeed",1.0f},
  7.          {"Name","新兵"}
  8.      }},
  9.      {AttrType.Recruit , new Dictionary<string, object>
  10.      {
  11.          {"MaxHp",200},
  12.          {"MoveSpeed",2.0f},
  13.          {"Name","中士"}
  14.      }},
  15.      {AttrType.Recruit , new Dictionary<string, object>
  16.      {
  17.          {"MaxHp",500},
  18.          {"MoveSpeed",3.0f},
  19.          {"Name","上士"}
  20.      }},  {AttrType.Recruit , new Dictionary<string, object>
  21.      {
  22.          {"MaxHp",1000},
  23.          {"MoveSpeed",4.0f},
  24.          {"Name","上尉"}
  25.      }},
  26. };
  27. public string GetName()
  28. {
  29.     return (string)Const.BaseAttrDict[baseAttrType]["Name"];
  30. }
  31. public int GetMapHp()
  32. {
  33.     return (int)Const.BaseAttrDict[baseAttrType]["MaxHp"];
  34. }
  35. public float GetMoveSpeed()
  36. {
  37.     return (float)Const.BaseAttrDict[baseAttrType]["MoveSpeed"];
  38. }
复制代码
这种写法有一个致命的问题:拆箱封箱(如果可以设置值)带来的性能消耗
在一个字典里存下各种类型的变量,被迫使用了object,但是再使用的时候,又要把object拆箱成对应的实际类型,这个配置字典方案只有在不会频繁调用这些属性的情况下才会用

使用享元模式,首先在设计上找到”可共享“的属性,在这个例子中是:maxHp,moveSpeed,name,将共享属性放到一起
  1. public class FlyweightAttr
  2. {
  3.     public int maxHp { get; set; }
  4.     public float moveSpeed { get; set; }
  5.     public string name { get; set; }
  6.     public FlyweightAttr(string name, int maxHp, float moveSpeed)
  7.     {
  8.         this.name = name;
  9.         this.maxHp = maxHp;
  10.         this.moveSpeed = moveSpeed;
  11.     }
  12. }
复制代码
士兵的属性类SoldierAttr持有FlyweightAttr这个引用,并包含不可共享的属性:hp和height
  1. public class SoldierAttr
  2. {
  3.     public int hp { get; set; }
  4.     public float height { get; set; }
  5.     public FlyweightAttr flyweightAttr { get; }
  6.     public SoldierAttr(FlyweightAttr flyweightAttr, int hp, float height)
  7.     {
  8.         this.flyweightAttr = flyweightAttr;
  9.         this.hp = hp;
  10.         this.height = height;
  11.     }
  12.    
  13.     public int GetMaxHp()
  14.     {
  15.         return flyweightAttr.maxHp;
  16.     }
  17.     public float GetMoveSpeed()
  18.     {
  19.         return flyweightAttr.moveSpeed;
  20.     }
  21.     public string GetName()
  22.     {
  23.         return flyweightAttr.name;
  24.     }
  25. }
复制代码
再增加一个工厂类来让外部容易获取到属性
  1. public class AttrFactory
  2. {
  3.     /// <summary>
  4.     /// 属性类型枚举
  5.     /// </summary>
  6.     public enum AttrType : uint
  7.     {
  8.         // 新兵
  9.         Recruit = 0,
  10.         // 中士
  11.         StaffSergeant,
  12.         // 上士
  13.         Sergeant,
  14.         // 上尉
  15.         Captian,
  16.     }
  17.     // 基础属性缓存
  18.     private Dictionary _flyweightAttrDB = null;
  19.    
  20.     public AttrFactory()
  21.     {
  22.         _flyweightAttrDB = new Dictionary();
  23.         _flyweightAttrDB.Add(AttrType.Recruit, new FlyweightAttr("士兵", 100, 1.0f));
  24.         _flyweightAttrDB.Add(AttrType.StaffSergeant, new FlyweightAttr("中士", 200, 2.0f));
  25.         _flyweightAttrDB.Add(AttrType.Sergeant, new FlyweightAttr("上士", 500, 3.0f));
  26.         _flyweightAttrDB.Add(AttrType.Captian, new FlyweightAttr("上尉", 1000, 4.0f));
  27.     }
  28.    
  29.     // 创建角色属性
  30.     public SoldierAttr CreateSoldierAttr(AttrType type, int hp, float height)
  31.     {
  32.         if (!_flyweightAttrDB.ContainsKey(type))
  33.         {
  34.             Debug.LogErrorFormat("{0}属性不存在", type);
  35.             return null;
  36.         }
  37.         FlyweightAttr flyweightAttr = _flyweightAttrDB[type];
  38.         SoldierAttr attr = new SoldierAttr(flyweightAttr, hp, height);
  39.         return attr;
  40.     }
  41. }
  42.  static void Main(string[] args){
  43.          //测试代码
  44.         AttrFactory factory = new AttrFactory();
  45.         for (int i = 0; i < _enemy_max; i++)
  46.         {
  47.             var values = Enum.GetValues(typeof(AttrFactory.AttrType));
  48.             AttrFactory.AttrType attrType = (AttrFactory.AttrType)values.GetValue(UnityEngine.Random.Range(0, 3));
  49.             SoldierAttr soldierAttr = factory.GetSoldierAttr(attrType, UnityEngine.Random.Range(0, 100), UnityEngine.Random.Range(155.0f, 190.0f));
  50.             objectsUseFlyweight.Add(soldierAttr);
  51.         }
  52.  }
复制代码
可以使用原始的属性类去对比性能
  1. public class HeavySoldierAttr : MonoBehaviour
  2. {
  3.     public int hp { get; set; }
  4.     public float height { get; set; }
  5.     public int maxHp { get; set; }
  6.     public float moveSpeed { get; set; }
  7.     public string name { get; set; }
  8.     public HeavySoldierAttr(int hp, float height, int maxHp, float moveSpeed, string name)
  9.     {
  10.         this.hp = hp;
  11.         this.height = height;
  12.         this.maxHp = maxHp;
  13.         this.moveSpeed = moveSpeed;
  14.         this.name = name;
  15.     }
  16. }
复制代码
观察者模式

***观察者模式(Observer Pattern)是一种行为设计模式,它定义了对象间的一种一对多的依赖关系,使得当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。这种模式又称为发布-订阅模式
***应用场景

  • 当一个对象的改变需要同时改变其他对象时。
  • 当需要在不同对象间保持同步时。
  • 当一个对象必须在另一个对象状态变化时自动更新时。
***实现方式

  • 主题(Subject):也称为“被观察者”,它维护一组观察者,提供用于注册和注销观察者的接口,并在状态改变时通知它们。
  • 观察者(Observer):提供一个更新接口,用于在主题状态改变时得到通知。
  • 具体主题(Concrete Subject):实现主题接口,当其状态改变时,向观察者发送通知。
  • 具体观察者(Concrete Observer):实现观察者接口,执行与主题状态变化相关的动作。
***优点

  • 实现对象间的松耦合:主题与观察者之间的耦合度低,主题不需要知道观察者的具体实现。
  • 支持广播通信:主题可以向所有注册的观察者广播通知,无需知道观察者的具体数量和类型。
  • 灵活性和可扩展性:可以动态地添加或删除观察者,而不需要修改主题的代码。
***缺点

  • 可能导致性能问题:如果观察者列表很长,通知所有观察者可能会导致性能下降。
  • 可能导致循环依赖:如果观察者和主题之间存在循环依赖,可能会导致复杂的状态更新问题
C#将它集成在了语言层面,event关键字
假设有一个角色血量变化时需要通知其他对象的游戏场景。可以使用观察者模式实现这种场景,让其他对象在角色血量变化时得到通知并作出相应的处理
  1. // 定义可观察的角色对象接口
  2. public interface ICharacterObservable
  3. {
  4.     //添加观察者
  5.     void AddObserver(ICharacterObserver observer);
  6.     //移除观察者
  7.     void RemoveObserver(ICharacterObserver observer);
  8.     // 通知所有观察者
  9.     void NotifyObservers();
  10. }
  11. // 定义观察者对象接口
  12. public interface ICharacterObserver
  13. {
  14.     // 角色血量变化时的处理方法
  15.     void OnCharacterHealthChanged(int newHealth);
  16. }
  17. // 具体的角色类,实现ICharacterObservable接口
  18. public class GameCharacter : ICharacterObservable
  19. {
  20. //存储实现了ICharacterObserver接口的观察者对象。这个集合用于管理所有对该角色对象感兴趣的观察者,以便在角色状态发生改变时通知它们
  21.     private List<ICharacterObserver> observers = new List<ICharacterObserver>();
  22.     private int health;
  23.     // 角色的血量属性
  24.     public int Health
  25.     {
  26.         get { return health; }
  27.         set
  28.         {
  29.             health = value;
  30.             NotifyObservers(); // 血量变化时通知所有观察者
  31.         }
  32.     }
  33.     // 添加观察者
  34.     public void AddObserver(ICharacterObserver observer)
  35.     {
  36.         observers.Add(observer);
  37.     }
  38.     // 移除观察者
  39.     public void RemoveObserver(ICharacterObserver observer)
  40.     {
  41.         observers.Remove(observer);
  42.     }
  43.     // 通知所有观察者
  44.     public void NotifyObservers()
  45.     {
  46.         foreach (var observer in observers)
  47.         {
  48.             observer.OnCharacterHealthChanged(health); // 通知观察者处理角色血量变化
  49.         }
  50.     }
  51. }
  52. // 具体的观察者类,实现ICharacterObserver接口
  53. public class EnemyAI : ICharacterObserver
  54. {
  55.     // 处理角色血量变化的方法
  56.     public void OnCharacterHealthChanged(int newHealth)
  57.     {
  58.         if (newHealth <= 0)
  59.         {
  60.             // 角色死亡时的处理逻辑
  61.             Console.WriteLine("Enemy AI: Character is dead, stop attacking!");
  62.         }
  63.         else
  64.         {
  65.             // 角色血量变化时的处理逻辑
  66.             Console.WriteLine("Enemy AI: Character health changed to " + newHealth);
  67.         }
  68.     }
  69. }
  70. // 使用示例
  71. GameCharacter player = new GameCharacter();
  72. EnemyAI enemyAI = new EnemyAI();
  73. player.AddObserver(enemyAI); // 将怪物AI作为观察者添加到角色对象中
  74. player.Health = 10; // 触发通知,输出 "Enemy AI: Character health changed to 10"
  75. player.Health = 0;  // 触发通知,输出 "Enemy AI: Character is dead, stop attacking!"
复制代码
单例模式

***使用单例(Singleton Pattern)意味着这个对象只有一个实例,这个实例是此对象自行构造的,并且可向全局提供
***应用场景

  • 当需要确保某个类只有一个实例时。
  • 当需要提供一个全局访问点来获取这个实例时。
  • 当实例化的成本较高,且只需要一个实例时。
***实现方式

  • 私有化构造函数:确保不能通过 new 关键字创建类的实例。
  • 提供一个私有静态变量:用于持有唯一的类实例。
  • 提供一个公有静态方法:用于获取类实例。如果实例不存在,则创建一个实例并返回;如果实例已存在,则直接返回。
***优点

  • 控制实例数量:确保类只有一个实例,避免资源浪费。
  • 快速访问:提供一个全局访问点来获取实例,方便使用。任何其他类都可以通过访问单例,使用它的公开变量和方法
  • 延迟初始化:实例化操作可以延迟到真正需要时才进行。
  • 减少代码复用,让专门的类处理专门的事情——例如让TimeLog类来记录日志,而不是把StreamWriter的代码写到每一个类里
***缺点

  • 滥用单例:因为实现简单,而且使用方便,所以有被滥用的趋势,导致系统设计不合理。
  • 测试困难:单例模式可能导致单元测试困难,因为它引入了全局状态。
  • 线程安全问题:每个线程都可以访问这个单例,会产生初始化、死锁等一系列问题,在多线程环境中,需要确保线程安全。
  • 滥用单例会促进耦合的发生,因为单例是全局可访问的,如果不该访问者访问了单例,就会造成过耦合——例如如果播放器允许单例,那石头碰撞地面后就可以直接调用播放器来播放声音,这在程序世界并不合理,而且会破坏架构
  • 如果很多很多类和对象调用了某个单例并做了一系列修改,那想理解具体发生了什么就困难了
书上一直强调不要使用单例,因为它是一个全局变量,全局变量促进了耦合,对并发也不友好,设置全局变量时,我们创建了一段内存,每个线程都能够访问和修改它,而不管它们是否知道其他线程正在操作它。这有可能导致死锁、条件竞争和其他一些难以修复的线程同步的Bug
TimeLogger.cs:实现单例实例
  1. using System;
  2. public class GameCharacter
  3. {
  4.     // 定义一个事件,事件的类型为EventHandler<int>
  5.     public event EventHandler<int> HealthChanged;
  6.     private int health;
  7.     public int Health
  8.     {
  9.         get { return health; }
  10.         set
  11.         {
  12.             health = value;
  13.             OnHealthChanged(health); // 在setter中调用事件触发方法
  14.         }
  15.     }
  16.     // 触发事件的方法
  17.     protected virtual void OnHealthChanged(int newHealth)
  18.     {
  19.         // 通过事件触发器调用事件,传递当前对象和新的血量值
  20.         HealthChanged?.Invoke(this, newHealth);
  21.     }
  22. }
  23. public class EnemyAI
  24. {
  25.     // 订阅GameCharacter对象的HealthChanged事件
  26.     public void Subscribe(GameCharacter character)
  27.     {
  28.         character.HealthChanged += CharacterHealthChanged;
  29.     }
  30.     // 事件处理方法
  31.     public void CharacterHealthChanged(object sender, int newHealth)
  32.     {
  33.         Console.WriteLine("Enemy AI: Character health changed to " + newHealth);
  34.     }
  35. }
  36. // 使用示例
  37. GameCharacter player = new GameCharacter();
  38. EnemyAI enemyAI = new EnemyAI();
  39. enemyAI.Subscribe(player); // 订阅事件
  40. player.Health = 10; // 输出 "Enemy AI: Character health changed to 10"
复制代码
Speaker.cs:
  1. //触发事件的具体主题
  2. public class Emitter : MonoBehaviour  
  3. {  
  4.   
  5.     public GameObject Ball;  
  6.   
  7.     void Start()  
  8.     {  
  9.         //First time wait 1 second for to the EmitBall method, then call at random intervals of 0.5-1.5 seconds  
  10.         InvokeRepeating("EmitBall", 1f, Random.Range(0.5f, 1.5f));  
  11.     }  
  12.   
  13.     void EmitBall()  
  14.     {  
  15.         GameObject go = Instantiate(Ball);  
  16.         go.GetComponent<Rigidbody>().velocity = Vector3.up * 2f;  
  17.         if (Radio.Instance.OnEmitEvent != null)//if Radio.Instance.OnEmitEvent is not null  
  18.         {  
  19.             Radio.Instance.OnEmitEvent(go.transform);  
  20.         }  
  21.     }  
  22. }
  23. //提供了一个全局的事件分发机制
  24. public class Radio : MonoBehaviour  
  25. {  
  26.   
  27.     public delegate void EmitHandler(Transform target);// Define a delegate type for the event  
  28.     public EmitHandler OnEmitEvent;// Create a new event with the delegate type  
  29.     public static Radio Instance;  
  30.   
  31.     void Awake()  
  32.     {  
  33.         Instance = this;  
  34.     }  
  35. }
  36. //观察者
  37. public class Shooter : MonoBehaviour  
  38. {  
  39.   
  40.     public GameObject Bullet;  
  41.   
  42.   
  43.     private void Start()  
  44.     {  
  45.         AddObserver();  
  46.     }  
  47.   
  48.     private void AddObserver()  
  49.     {  
  50.         Radio.Instance.OnEmitEvent += Shoot;//subscribe to the event  
  51.     }  
  52.   
  53.     private void Shoot(Transform target)  
  54.     {  
  55.         GameObject go = Instantiate(Bullet, transform.position, Quaternion.identity);  
  56.         go.GetComponent<Rigidbody>().velocity = (target.position - transform.position).normalized * 30f;  
  57.     }  
  58. }
复制代码
状态模式

***现在状态和条件决定对象的新状态,状态决定行为(Unity内AnimationController就是状态机)
状态模式(State Pattern)允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。状态模式将对象的行为封装在不同的状态对象中,将对象的状态从对象中分离出来,客户端无需关心对象的当前状态和状态的转换
***应用场景

  • 当一个对象的行为取决于它的状态,并且它必须在运行时根据状态改变它的行为时。
  • 当代码中存在大量条件语句,且这些条件语句依赖于对象的状态时。
  • 如果对象需要根据自身当前状态进行不同行为,同时状态的数量非常多且与状态相关的代码会频繁变更的话。
***实现方式

  • 状态接口(State Interface):定义状态类所需的方法,这些方法描述了对象在该状态下应该执行的行为。
  • 具体状态类(Concrete State Classes):实现状态接口,为对象在不同状态下定义具体的行为。
  • 上下文类(Context):包含一个状态对象的引用,并在状态改变时更新其行为。
***优点

  • 代码结构化:将状态相关的行为封装在具体的状态类中,使得状态转换逻辑清晰。
  • 易于维护和扩展:每个状态只需要关心自己内部的实现,而不会影响到其他的,耦合降低。
  • 增加新状态操作简单:可以将不同的状态隔离,每个状态都是一个单独的类,可以将各种状态的转换逻辑分布到状态的子类中,减少相互依赖。
***缺点

  • 类数目增多:状态类数目较多,增加了系统的复杂性。
  • 状态转换逻辑复杂:如果状态转换逻辑复杂,状态类之间的依赖关系可能会变得复杂。
  • 结构与实现复杂:状态模式的结构与实现都较为复杂,如果使用不当将导致程序结构和代码的混乱
LightSwitchCaseight根据当前状态切换到下一个状态,并设置相应的灯光颜色
  1. title: 注意
  2. 一定要及时删除失效观察者,以及被观察者失效删除对应的观察者对象
  3. 观察者模式非常适合于一些不相关的模块之间的通信问题。它不适合于单个紧凑的模块内部的通信
复制代码
LightStateClass和TrafficState抽象类:
  1. using UnityEngine;  
  2.   
  3. namespace PrototypePattern.MonsterSpawner  
  4. {  
  5.     public class SpawnController : MonoBehaviour  
  6.     {  
  7.         // 每种类型的怪物都有一个对应的原型  
  8.         private Ghost ghostPrototype;  
  9.         private Demon demonPrototype;  
  10.         private Sorcerer sorcererPrototype;  
  11.   
  12.         // monsterSpawners 数组保存了所有可用的 Spawner 实例  
  13.         private Spawner[] monsterSpawners;  
  14.   
  15.         private void Start()  
  16.         {  
  17.             // 初始化每种怪物类型的原型。  
  18.             ghostPrototype = new Ghost(15, 3);  
  19.             demonPrototype = new Demon(11, 7);  
  20.             sorcererPrototype = new Sorcerer(4, 11);  
  21.   
  22.             // 初始化 Spawner 数组,为每种怪物类型提供一个 Spawner            monsterSpawners = new Spawner[] {  
  23.                 new(ghostPrototype),  
  24.                 new(demonPrototype),  
  25.                 new(sorcererPrototype),  
  26.             };  
  27.         }  
  28.   
  29.         private void Update()  
  30.         {  
  31.             if (Input.GetKeyDown(KeyCode.Space))  
  32.             {  
  33.                 var ghostSpawner = new Spawner(ghostPrototype);  
  34.                 var newGhost = ghostSpawner.SpawnMonster() as Ghost;  
  35.   
  36.                 // 调用新鬼魂的 Talk 方法,输出一条消息到控制台  
  37.                 newGhost.Talk();  
  38.   
  39.                 // 随机选择一个 Spawner 来生成一个随机类型的怪物  
  40.                 Spawner randomSpawner = monsterSpawners[Random.Range(0, monsterSpawners.Length)];  
  41.                 _Monster randomMonster = randomSpawner.SpawnMonster();  
  42.   
  43.                 // 调用新生成的随机怪物的 Talk 方法。  
  44.                 randomMonster.Talk();  
  45.             }  
  46.         }  
  47.     }  
  48. }
  49. namespace PrototypePattern.MonsterSpawner  
  50. {  
  51.     // 使用原型设计模式,允许从一个原型对象生成新的对象实例  
  52.     public class Spawner  
  53.     {  
  54.         private _Monster prototype; // 保存要克隆的原型怪物  
  55.   
  56.         // 构造函数接收一个原型怪物作为参数并保存它。  
  57.         public Spawner(_Monster prototype)  
  58.         {  
  59.             this.prototype = prototype;  
  60.         }  
  61.   
  62.         // SpawnMonster 方法返回原型怪物的一个克隆。  
  63.         public _Monster SpawnMonster()  
  64.         {  
  65.             return prototype.Clone();  
  66.         }  
  67.     }  
  68. }
  69. namespace PrototypePattern.MonsterSpawner  
  70. {  
  71.     public abstract class _Monster  
  72.     {  
  73.         // Clone 方法实现了原型设计模式,派生类应该重写此方法以返回自身的克隆。  
  74.         public abstract _Monster Clone();  
  75.   
  76.         // Talk 方法是一个抽象方法,派生类应根据自己的特性实现不同的对话内容。  
  77.         public abstract void Talk();  
  78.     }  
  79. }
  80. using UnityEngine;  
  81.   
  82. namespace PrototypePattern.MonsterSpawner  
  83. {  
  84.     public class Sorcerer : _Monster  
  85.     {  
  86.         private int health;  
  87.         private int speed;  
  88.   
  89.         private static int sorcererCounter = 0;  
  90.   
  91.         public Sorcerer(int health, int speed)  
  92.         {  
  93.             this.health = health;  
  94.             this.speed = speed;  
  95.             sorcererCounter += 1;  
  96.         }  
  97.   
  98.         public override _Monster Clone()  
  99.         {  
  100.             return new Sorcerer(health, speed);  
  101.         }  
  102.   
  103.         public override void Talk()  
  104.         {  
  105.             Debug.Log($"Hello this is Sorcerer number {sorcererCounter}. My health is {health} and my speed is {speed}");  
  106.         }  
  107.     }  
  108. }
  109. using UnityEngine;  
  110.   
  111. namespace PrototypePattern.MonsterSpawner  
  112. {  
  113.     public class Ghost : _Monster  
  114.     {  
  115.         private int health;  
  116.         private int speed;  
  117.         private static int ghostCounter = 0;  
  118.   
  119.         public Ghost(int health, int speed)  
  120.         {  
  121.             this.health = health;  
  122.             this.speed = speed;  
  123.             ghostCounter += 1;  
  124.         }  
  125.   
  126.         public override _Monster Clone()  
  127.         {  
  128.             return new Ghost(health, speed);  
  129.         }  
  130.   
  131.         public override void Talk()  
  132.         {  
  133.             Debug.Log($"Hello this is Ghost number {ghostCounter}. My health is {health} and my speed is {speed}");  
  134.         }  
  135.     }  
  136. }
  137. using UnityEngine;  
  138.   
  139. namespace PrototypePattern.MonsterSpawner  
  140. {  
  141.     public class Demon : _Monster  
  142.     {  
  143.         private int health;  
  144.         private int speed;  
  145.         private static int demonCounter = 0;  
  146.   
  147.         public Demon(int health, int speed)  
  148.         {  
  149.             this.health = health;  
  150.             this.speed = speed;  
  151.             demonCounter += 1;  
  152.         }  
  153.   
  154.         public override _Monster Clone()  
  155.         {  
  156.             return new Demon(health, speed);  
  157.         }  
  158.   
  159.         public override void Talk()  
  160.         {  
  161.             Debug.Log($"Hello this is Demon number {demonCounter}. My health is {health} and my speed is {speed}");  
  162.         }  
  163.     }  
  164. }
复制代码
交通灯状态类ass,Passblink,Wait,Stop
  1. {  
  2.   "dragons": [  
  3.     {  
  4.       "name": "FatDragon",  
  5.       "scale": {  
  6.         "x": 4,  
  7.         "y": 1,  
  8.         "z": 1  
  9.       }  
  10.     },  
  11.     {  
  12.       "name": "TallDragon",  
  13.       "scale": {  
  14.         "x": 1,  
  15.         "y": 1,  
  16.         "z": 3  
  17.       }  
  18.     },  
  19.     {  
  20.       "name": "LongDragon",  
  21.       "scale": {  
  22.         "x": 1,  
  23.         "y": 4,  
  24.         "z": 1  
  25.       }  
  26.     },  
  27.     {  
  28.       "name": "Dragon",  
  29.       "scale": {  
  30.         "x": 1,  
  31.         "y": 1,  
  32.         "z": 1  
  33.       }  
  34.     },  
  35.     {  
  36.       "name": "LittleDragon",  
  37.       "scale": {  
  38.         "x": 0.5,  
  39.         "y": 0.5,  
  40.         "z": 0.5  
  41.       }  
  42.     },  
  43.     {  
  44.       "name": "HugeDragon",  
  45.       "scale": {  
  46.         "x": 3,  
  47.         "y": 3,  
  48.         "z": 3  
  49.       }  
  50.     }  
  51.   ]  
  52. }
复制代码
双缓冲模式

***双缓冲模式(Double Buffering)是一种通过设置两个独立缓冲区来管理数据读写的技术。在双缓冲机制中,系统在读写缓冲区之间进行切换,使得生产者和消费者可以分别操作不同的缓冲区,避免了直接冲突

  • ***当一个缓冲准备好后才会被使用——就像一个集装箱装满才会发货一样;当一个缓冲被使用时另一个处于准备状态,就形成了双缓冲
  • ***在渲染中广泛使用,一帧准备好后才会被渲染到屏幕上——所以准备时间太长就会导致帧率下降
诸如计算机显示器的显示设备在每一时刻仅绘制一个像素.它会从左到右地扫描屏幕中每行中的像素,从上至下扫描屏幕上的每一行.当扫描至屏幕的右下角时,将重定位至屏幕的左上角并重复上面的行为
绘制所用的像素信息大多从帧缓冲区(framebuffer)中获知.帧缓冲区是RAM中存储像素的一个数组
***应用

  • 图形渲染:用于防止显示图形时的闪烁延迟等不良体验。
  • 音频处理和数据采集:减少刷新带来的显示闪烁或音频中断,提升系统的响应速度和稳定性。
  • 多线程环境:通过分离读写操作,提升系统性能并减少数据竞争。
***数据结构

  • 双缓冲区由两个缓冲区组成,分别称为A缓冲区和B缓冲区。在数据传输过程中,发送方先将数据存储在A缓冲区,接收方从B缓冲区中读取数据。当一个缓冲区的数据传输完成后,再通知发送方可以将下一批数据存储在另一个缓冲区中。
***优点

  • 减少数据竞争:双缓冲通过将读写分离,确保了生产者和消费者操作不同的缓冲区,从而避免数据竞争。
  • 提升性能:通过异步读写的方式减少了等待时间,有效提升了系统的吞吐量。
  • 满足实时性需求:在实时系统中,数据的快速更新和显示尤为重要,双缓冲能够减少刷新带来的显示闪烁或音频中断
***示例1:任务调度系统
Schedule:实现任务的调度功能
  1. using UnityEngine;  
  2.   
  3. [System.Serializable]  
  4. public class DragonData  
  5. {  
  6.     public string name;  
  7.     public Vector3 scale;  
  8. }  
  9.   
  10. public abstract class DragonPrototype : MonoBehaviour  
  11. {  
  12.     protected string Name;  
  13.     protected Vector3 Scale;  
  14.   
  15.     public virtual void SetData(DragonData data)  
  16.     {  
  17.         Name = data.name;  
  18.         Scale = data.scale;  
  19.         transform.localScale = Scale;  
  20.         gameObject.name = Name;  
  21.     }  
  22.   
  23.     public abstract DragonPrototype Clone();  
  24. }
复制代码
Task:一个序列化类,表示一个单独的任务
  1. using UnityEngine;  
  2.   
  3. public class Dragon : DragonPrototype  
  4. {  
  5.     void Start()  
  6.     {  
  7.         Invoke(nameof(DestroyThis), 10f);  
  8.     }  
  9.   
  10.     private void DestroyThis()  
  11.     {  
  12.         Destroy(gameObject);  
  13.     }  
  14.   
  15.     public override DragonPrototype Clone()  
  16.     {  
  17.         return Instantiate(this) as DragonPrototype;  
  18.     }  
  19.   
  20.     void Update()  
  21.     {  
  22.         transform.Translate(Vector3.up * (-Time.deltaTime * 2));  
  23.     }  
  24. }
复制代码
TaskPanel:Unity 编辑器中的自定义窗口,用来创建用户界面来管理任务,主要用于学习,实际的任务调度应由代码实现
  1. using System.Collections.Generic;  
  2. using System.IO;  
  3. using UnityEngine;  
  4.   
  5. public class Spawner : MonoBehaviour  
  6. {  
  7.     public DragonPrototype Prototype;  
  8.     public float GapTime = 1;  
  9.   
  10.     private List<DragonData> dragons;  
  11.   
  12.     void Start()  
  13.     {  
  14.         LoadDragonsFromJson(Application.dataPath + @"\004PrototypePattern\Dragons.json");  
  15.         InvokeRepeating(nameof(SpawnObj), 0, GapTime);  
  16.     }  
  17.   
  18.     private void LoadDragonsFromJson(string path)  
  19.     {  
  20.         string json = File.ReadAllText(path);  
  21.         var dragonsWrapper = JsonUtility.FromJson<DragonsWrapper>(json);  
  22.         if (dragonsWrapper != null && dragonsWrapper.dragons != null && dragonsWrapper.dragons.Count > 0)  
  23.         {  
  24.             dragons = dragonsWrapper.dragons;  
  25.         }  
  26.         else  
  27.         {  
  28.             Debug.LogError("Dragons list is empty or null.");  
  29.         }  
  30.     }  
  31.   
  32.     void SpawnObj()  
  33.     {  
  34.         if (dragons == null || dragons.Count == 0) return;  
  35.   
  36.         int target = Random.Range(0, dragons.Count);  
  37.         DragonData dragonData = dragons[target];  
  38.   
  39.         DragonPrototype newDragon = Prototype.Clone() as DragonPrototype;  
  40.         newDragon.SetData(dragonData);  
  41.         newDragon.transform.position = transform.position;  
  42.     }  
  43.   
  44.     [System.Serializable]  
  45.     public class DragonsWrapper  
  46.     {  
  47.         public List<DragonData> dragons;  
  48.     }  
  49. }
复制代码
游戏循环

1. FPS依赖于恒定游戏速度
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using UnityEngine;  
  6.   
  7. public class TimeLogger : MonoBehaviour  
  8. {  
  9.   
  10.     public static TimeLogger Instance;  
  11.     private StreamWriter mSW;// StreamWriter 用于写入文件  
  12.   
  13.     void Awake()  
  14.     {  
  15.         Instance = this;  
  16.         LoggerInit(Application.dataPath + @"\005SingletonPattern\Log.txt");  
  17.     }  
  18.   
  19.     void LoggerInit(string path)  
  20.     {  
  21.         if (mSW == null)  
  22.         {  
  23.             mSW = new StreamWriter(path);  
  24.         }  
  25.     }  
  26.   
  27.     public void WhiteLog(string info)  
  28.     {  
  29.         mSW.Write(DateTime.Now + ": " + info + "\n");  
  30.     }  
  31.   
  32.     private void OnEnable()  
  33.     {  
  34.         LoggerInit(Application.dataPath + @"\005SingletonPattern\Log.txt");  
  35.     }  
  36.   
  37.     private void OnDisable()  
  38.     {  
  39.         mSW.Close();  
  40.     }  
  41. }
复制代码
两个重要变量来控制恒定帧数:
next_game_tick:这一帧完成的时间点
sleep_time:若大于0,则目前时间没到完成这一帧的时间点。启用Sleep等待时间点的到达;若小于0,则该帧的工作没完成。
恒定帧数的好处:防止整个游戏因为跳帧而引起画面的撕裂。性能较低的硬件会显得更慢;而性能高的硬件则浪费了硬件资源
2.游戏速度取决于可变FPS
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class Speaker : MonoBehaviour  
  6. {  
  7.   
  8.     public string SpeakerName;  
  9.     public float GapTime = 1;  
  10.     private int index = 1;  
  11.   
  12.     void Start()  
  13.     {  
  14.         InvokeRepeating("Speak", 0, GapTime);  
  15.     }  
  16.   
  17.     void Speak()  
  18.     {  
  19.         string content = "I'm " + SpeakerName + ". (Index : " + index + ")";  
  20.         Debug.Log(content);  
  21.         TimeLogger.Instance.WhiteLog(content);  
  22.         index++;  
  23.     }  
  24. }
复制代码
两个重要变量来控制恒定帧数:
prev_frame_tick:上一帧完成的时间点
curr_frame_tick:目前的时间点
curr_frame_tick和prev_frame_tick的差即为一帧所需的时间,根据这一个变量,每一帧的时间是不一样的。FPS也是可变的。
缓慢的硬件有时会导致某些点的某些延迟,游戏变得卡顿。
快速的硬件也会出现问题,帧数可变意味着在计算时不可避免地会有计算误差。
这种游戏循环一见钟情似乎很好,但不要被愚弄。慢速和快速硬件都可能导致游戏出现严重问题。此外,游戏更新功能的实现比使用固定帧速率时更难,为什么要使用它?
3. 具有最大FPS的恒定游戏速度
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class LightSwitchCase : MonoBehaviour {  
  6.   
  7.     public LightState CurrentState = LightState.Off;  
  8.   
  9.     private Light mLight;  
  10.     private Material mMat;  
  11.     private static readonly int EmissionColor = Shader.PropertyToID("_EmissionColor");  
  12.   
  13.     public enum LightState  
  14.     {  
  15.         Off,  
  16.         Warm,  
  17.         White,  
  18.         WarmWhite  
  19.     }  
  20.   
  21.     private void Awake()  
  22.     {  
  23.         mLight = GetComponent<Light>();  
  24.         mMat = GetComponentInChildren<Renderer>().material;  
  25.     }  
  26.   
  27.     public void OnChangeState()  
  28.     {  
  29.         //状态转换  
  30.         switch (CurrentState)  
  31.         {  
  32.             case LightState.Off:  
  33.                 CurrentState = LightState.Warm;  
  34.                 break;  
  35.             case LightState.Warm:  
  36.                 CurrentState = LightState.WarmWhite;  
  37.                 break;  
  38.             case LightState.WarmWhite:  
  39.                 CurrentState = LightState.White;  
  40.                 break;  
  41.             case LightState.White:  
  42.                 CurrentState = LightState.Off;  
  43.                 break;  
  44.             default:  
  45.                 CurrentState = LightState.Off;  
  46.                 break;  
  47.         }  
  48.         //状态行为  
  49.         switch (CurrentState)  
  50.         {  
  51.             case LightState.Off:  
  52.                 mLight.color = Color.black;  
  53.                 mMat.SetColor(EmissionColor, mLight.color);  
  54.                 break;  
  55.             case LightState.Warm:  
  56.                 mLight.color = new Color(0.8f, 0.5f, 0);  
  57.                 mMat.SetColor(EmissionColor, mLight.color);  
  58.                 break;  
  59.             case LightState.WarmWhite:  
  60.                 mLight.color = new Color(1, 0.85f, 0.6f);  
  61.                 mMat.SetColor(EmissionColor, mLight.color);  
  62.                 break;  
  63.             case LightState.White:  
  64.                 mLight.color = new Color(0.8f, 0.8f, 0.8f);  
  65.                 mMat.SetColor(EmissionColor, mLight.color);  
  66.                 break;  
  67.             default:  
  68.                 mLight.color = Color.black;  
  69.                 mMat.SetColor(EmissionColor, mLight.color);  
  70.                 break;  
  71.         }  
  72.     }  
  73. }
复制代码
MAX_FRAMESKIP : 帧数缩小的最低倍数
最高帧数为50帧,当帧数过低时,渲染帧数将降低(display_game()),最低可至5帧(最高帧数缩小10倍),更新帧数保持不变(update_game())
在慢速硬件上,每秒帧数会下降,但游戏本身有望以正常速度运行。
游戏在快速硬件上没有问题,但是像第一个解决方案一样,你浪费了很多宝贵的时钟周期,可以用于更高的帧速率。在快速更新速率和能够在慢速硬件上运行之间找到平衡点至关重要。(最重要的原因是限制了帧数)
缺点与第一种方案相似
4.恒定游戏速度独立于可变FPS
  1. using UnityEngine;  
  2.   
  3. public class LightStateClass : MonoBehaviour  
  4. {  
  5.   
  6.     public GameObject GreenLightObj;  
  7.     public GameObject YellowLightObj;  
  8.     public GameObject RedLightObj;  
  9.     //灯光材质  
  10.     private Material GreenLight;  
  11.     private Material YellowLight;  
  12.     private Material RedLight;  
  13.     //当前灯光状态  
  14.     private TrafficState TrafficLight;  
  15.   
  16.     void Start()  
  17.     {  
  18.         GreenLight = GreenLightObj.GetComponent<Renderer>().material;  
  19.         YellowLight = YellowLightObj.GetComponent<Renderer>().material;  
  20.         RedLight = RedLightObj.GetComponent<Renderer>().material;  
  21.         SetState(new Pass());  
  22.   
  23.     }  
  24.   
  25.     void Update()  
  26.     {  
  27.         TrafficLight.ContinuousStateBehaviour(this, GreenLight, YellowLight, RedLight);  
  28.     }  
  29.   
  30.     public void SetState(TrafficState state)  
  31.     {  
  32.         TrafficLight = state;  
  33.         TrafficLight.StateStart(GreenLight, YellowLight, RedLight);  
  34.     }  
  35. }  
  36.   
  37. public abstract class TrafficState  
  38. {  
  39.     public float Duration;  
  40.     public float Timer;  
  41.     public static readonly int EmissionColor = Shader.PropertyToID("_EmissionColor");//控制材质自发光颜色属性ID  
  42.     public virtual void StateStart(Material GreenLight, Material YellowLight, Material RedLight)  
  43.     {  
  44.         Timer = Time.time;//当前时间  
  45.     }  
  46.     public abstract void ContinuousStateBehaviour(LightStateClass mLSC, Material GreenLight, Material YellowLight, Material RedLight);  
  47. }
复制代码
渲染帧数是预测与插值实现的。 interpolation 计算等价的帧数
游戏循环比想象更多。有一个应该避免的,这就是变量FPS决定游戏速度的那个。恒定的帧速率对于移动设备来说可能是一个很好而简单的解决方案,但是当你想要获得硬件所拥有的一切时,最好使用FPS完全独立于游戏速度的游戏循环,使用高帧速率的预测功能。如果您不想使用预测功能,可以使用最大帧速率,但为慢速和快速硬件找到合适的游戏更新速率可能会非常棘手
迭代器模式

***迭代器模式(Iterator Pattern)是一种行为型设计模式,它提供了一种方法来顺序访问一个聚合对象中的各个元素,而不暴露其内部的表示
迭代器模式在unity游戏开发中应用非常多
.NET框架提供IEnumerable和IEnumerator接口
一个collection要支持Foreach进行遍历,就必须实现IEnumerable,并以某种方式返回迭代器对象:IEnumerable
***应用场景

  • 当需要为聚合对象提供多种遍历方式时。
  • 当需要为遍历不同的聚合结构提供一个统一的接口时。
  • 当访问一个聚合对象的内容而无须暴露其内部细节的表示时。
***数据结构

  • 迭代器(Iterator):定义访问和遍历元素的接口,通常包含 hasNext()、next() 等方法。
  • 具体迭代器(ConcreteIterator):实现迭代器接口,并跟踪当前位置,以便在聚合对象中遍历元素。
  • 聚合(Aggregate):定义创建相应迭代器对象的接口,通常包含一个返回迭代器实例的方法,如 iterator()。
  • 具体聚合(ConcreteAggregate):实现创建相应迭代器的接口,返回具体迭代器的一个实例。
***实现方式

  • 迭代器模式通过将聚合对象的遍历行为分离出来,抽象成迭代器类来实现。其目的是在不暴露聚合对象的内部结构的情况下,让外部代码透明地访问聚合的内部数据。
***优点

  • 封装性:迭代器模式将遍历集合的责任封装到一个单独的对象中,保护了集合的内部表示,提高了代码的封装性。
  • 扩展性:迭代器模式允许在不修改聚合类代码的情况下,增加新的遍历方式。只需要实现一个新的迭代器类即可。
  • 灵活性:迭代器模式提供了多种遍历方式,如顺序遍历、逆序遍历、多线程遍历等,可以根据实际需求选择适合的遍历方式
Unity的Transform使用了迭代器模式:
  1. using UnityEngine;  
  2.   
  3. public class Pass : TrafficState  
  4. {  
  5.     public Pass()  
  6.     {  
  7.         Duration = 2;  
  8.     }  
  9.   
  10.     public override void StateStart(Material GreenLight, Material YellowLight, Material RedLight)  
  11.     {  
  12.         base.StateStart(GreenLight, YellowLight, RedLight);  
  13.         GreenLight.SetColor(EmissionColor, Color.green);  
  14.         YellowLight.SetColor(EmissionColor, Color.black);  
  15.         RedLight.SetColor(EmissionColor, Color.black);  
  16.     }  
  17.     public override void ContinuousStateBehaviour(LightStateClass mLSC, Material GreenLight, Material YellowLight, Material RedLight)  
  18.     {  
  19.         if (Time.time > Timer + Duration)  
  20.         {  
  21.             mLSC.SetState(new PassBlink());  
  22.         }  
  23.     }  
  24. }
  25. using UnityEngine;  
  26.   
  27. public class PassBlink : TrafficState  
  28. {  
  29.     private bool On = true;  
  30.     private float BlinkTimer = 0;  
  31.     private float BlinkInterval = 0.2f;  
  32.   
  33.     public PassBlink()  
  34.     {  
  35.         Duration = 1;  
  36.     }  
  37.   
  38.     public override void StateStart(Material GreenLight, Material YellowLight, Material RedLight)  
  39.     {        base.StateStart(GreenLight, YellowLight, RedLight);    }  
  40.     private static void SwitchGreen(Material GreenLight, bool open)  
  41.     {  
  42.         Color color = open ? Color.green : Color.black;  
  43.         GreenLight.SetColor(EmissionColor, color);  
  44.     }  
  45.   
  46.     public override void ContinuousStateBehaviour(LightStateClass mLSC, Material GreenLight, Material YellowLight, Material RedLight)  
  47.     {  
  48.         if (Time.time > Timer + Duration)  
  49.         {  
  50.             mLSC.SetState(new Wait());  
  51.         }  
  52.         if (Time.time > BlinkTimer+BlinkInterval)  
  53.         {  
  54.             On = !On;  
  55.             BlinkTimer = Time.time;  
  56.             SwitchGreen(GreenLight,On);  
  57.         }  
  58.     }  
  59. }
  60. using UnityEngine;  
  61.   
  62. public class Wait : TrafficState  
  63. {  
  64.     public Wait()  
  65.     {  
  66.         Duration = 1;  
  67.     }  
  68.   
  69.     public override void StateStart(Material GreenLight, Material YellowLight, Material RedLight)  
  70.     {  
  71.         base.StateStart(GreenLight, YellowLight, RedLight);  
  72.         GreenLight.SetColor(EmissionColor, Color.black);  
  73.         YellowLight.SetColor(EmissionColor, Color.yellow);  
  74.         RedLight.SetColor(EmissionColor, Color.black);  
  75.     }  
  76.     public override void ContinuousStateBehaviour(LightStateClass mLSC, Material GreenLight, Material YellowLight, Material RedLight)  
  77.     {  
  78.         if (Time.time > Timer + Duration)  
  79.         {  
  80.             mLSC.SetState(new Stop());  
  81.         }  
  82.     }  
  83. }
  84. using UnityEngine;  
  85.   
  86. public class Stop : TrafficState  
  87. {  
  88.     public Stop()  
  89.     {  
  90.         Duration = 1;  
  91.     }  
  92.   
  93.     public override void StateStart(Material GreenLight, Material YellowLight, Material RedLight)  
  94.     {  
  95.         base.StateStart(GreenLight, YellowLight, RedLight);  
  96.         GreenLight.SetColor(EmissionColor, Color.black);  
  97.         YellowLight.SetColor(EmissionColor, Color.black);  
  98.         RedLight.SetColor(EmissionColor, Color.red);  
  99.     }  
  100.     public override void ContinuousStateBehaviour(LightStateClass mLSC, Material GreenLight, Material YellowLight, Material RedLight)  
  101.     {  
  102.         if (Time.time > Timer + Duration)  
  103.         {  
  104.             mLSC.SetState(new Pass());  
  105.         }  
  106.     }  
  107. }
复制代码
实现迭代器模式:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class Schedule : MonoBehaviour  
  6. {  
  7.     // 双缓冲列表,用于防止在计时器回调期间直接修改计时器队列  
  8.     [SerializeField] private List<Task> _Front; // _Front 用于收集新添加的任务  
  9.     [SerializeField] private List<Task> _Back; // _Back 用于迭代和处理任务  
  10.   
  11.     // 收集需要被移除的 Schedule 对象,避免在迭代过程中直接修改 _Back 列表  
  12.     [SerializeField] private List<Task> _Garbage;  
  13.   
  14.     private static Schedule Instance;  
  15.   
  16.     private void Awake()  
  17.     {  
  18.         if (Instance == null)  
  19.             Instance = this;  
  20.         DontDestroyOnLoad(this);  
  21.         _Front = new List<Task>();  
  22.         _Back = new List<Task>();  
  23.         _Garbage = new List<Task>();  
  24.     }  
  25.   
  26.     // 设置一个新的调度任务  
  27.     public Task SetSchedule(string bindName, float time, Action<Task> callback, bool usingWorldTimeScale = false  
  28.         , bool isLoop = false, bool isPause = false)  
  29.     {  
  30.         // 创建一个新的 Schedule 实例,并将其添加到 _Front 队列中  
  31.         var sd = new Task(bindName, time, callback, usingWorldTimeScale, isLoop, isPause);  
  32.         _Front.Add(sd);  
  33.         Debug.Log("Schedule: " + _Front.Count + " tasks added.");  
  34.         return sd;  
  35.     }  
  36.   
  37.     public void SetSchedule(Task sd)  
  38.     {  
  39.         if (_Back.Contains(sd))  
  40.         {  
  41.             // 如果已经在 _Back 中,则不需要再次添加  
  42.             return;  
  43.         }  
  44.   
  45.         if (!_Front.Contains(sd))  
  46.         {  
  47.             // 如果不在 _Front 中,则添加回去  
  48.             _Front.Add(sd);  
  49.         }  
  50.     }  
  51.   
  52.     public void RemoveSchedule(Task sd)  
  53.     {  
  54.         if (sd == null) return;  
  55.         _Front.Remove(sd);  
  56.         _Back.Remove(sd);  
  57.     }  
  58.   
  59.   
  60.     // 更新所有调度任务的状态  
  61.     private void Update()  
  62.     {  
  63.         // 将 _Front 中的所有新任务转移到 _Back,然后清空 _Front        if (_Front.Count > 0)  
  64.         {  
  65.             _Back.AddRange(_Front);  
  66.             _Front.Clear();  
  67.         }  
  68.   
  69.         float dt = Time.deltaTime; // 获取自上次调用以来的时间差  
  70.   
  71.         foreach (Task s in _Back)  
  72.         {  
  73.             // 检查任务是否已被取消,若取消则标记为垃圾并跳过  
  74.             if (s.Canceled)  
  75.             {  
  76.                 _Garbage.Add(s);  
  77.                 continue;  
  78.             }  
  79.   
  80.             if (s.IsPause)  
  81.             {  
  82.                 continue;  
  83.             }  
  84.   
  85.             Task sd = s;  
  86.   
  87.             // 计算剩余时间,是否使用世界时间比例  
  88.             float tmpTime = sd.Time;  
  89.             var InGameTimeScale = 1.0f; // 假设游戏未暂停,时间比例为 1.0f,可以被加快或减慢  
  90.             tmpTime -= sd.UsingWorldTimeScale ? dt * InGameTimeScale : dt;  
  91.   
  92.             // 更新 Schedule 的剩余时间  
  93.             sd.ResetTime(tmpTime);  
  94.   
  95.   
  96.             if (tmpTime > 0) continue;  
  97.             // 如果时间已经到了或超过了触发点,则执行回调函数  
  98.             s.Callback?.Invoke(s);  
  99.             if (s.IsLoop)  
  100.             {  
  101.                 s.ResetTime(s.OriginalTime); // 重置时间为原始时间  
  102.             }  
  103.             else  
  104.             {  
  105.                 _Garbage.Add(s); // 标记为垃圾  
  106.             }  
  107.         }  
  108.   
  109.         // 清理已完成或被取消的任务  
  110.         Debug.Log("Schedule: " + _Garbage.Count + " garbage tasks removed.");  
  111.         foreach (Task s in _Garbage)  
  112.         {  
  113.             if (_Back.Contains(s))  
  114.             {  
  115.                 _Back.Remove(s); // 从 _Back 移除垃圾任务  
  116.             }  
  117.         }  
  118.   
  119.         _Garbage.Clear(); // 清空垃圾列表  
  120.     }  
  121. }
复制代码
  1. using System;  
  2.   
  3. [Serializable]  
  4. public class Task  
  5. {  
  6.     public bool Canceled; // 是否取消任务  
  7.     public float OriginalTime; // 存储原始时间  
  8.     public float Time; // 任务持续时间  
  9.     public bool UsingWorldTimeScale; // 是否使用世界时间比例  
  10.     public bool IsLoop; // 是否循环  
  11.     public bool IsPause; // 是否暂停  
  12.     public string TaskName; // 任务名称  
  13.     public Action<Task> Callback; // 任务完成时的回调函数  
  14.   
  15.     public Task(string taskTaskName, float time, Action<Task> callback, bool usingWorldTimeScale = false  
  16.         , bool isLoop = false, bool isPause = false)  
  17.     {  
  18.         Time = time;  
  19.         OriginalTime = time;  
  20.         UsingWorldTimeScale = usingWorldTimeScale;  
  21.         TaskName = taskTaskName;  
  22.         IsLoop = isLoop;  
  23.         IsPause = isPause;  
  24.         Callback = callback;  
  25.     }  
  26.   
  27.     public Task(float t, Action<Task> callback)  
  28.     {  
  29.         Time = t;  
  30.         Callback = callback;  
  31.     }  
  32.   
  33.     public void Cancel()  
  34.     {  
  35.         Canceled = true;  
  36.     }  
  37.   
  38.     public void ResetTime(float t)  
  39.     {  
  40.         Time = t;  
  41.     }  
  42. }
复制代码
  1. using System;  
  2. using UnityEngine;  
  3. using UnityEditor;  
  4.   
  5. public class TaskPanel : EditorWindow  
  6. {  
  7.     public string taskName = "New Task";  
  8.     public float time = 1.0f;  
  9.     public bool usingWorldTimeScale = false;  
  10.     public bool isLoop = false;  
  11.     public bool isPause = false;  
  12.     public int selectedCallbackIndex = 0; // 用于存储选中的回调函数索引  
  13.   
  14.     private Schedule schedule;  
  15.     private string[] callbackFunctionNames; // 存储回调函数名称的数组  
  16.   
  17.     [MenuItem("Tools/Task Panel")]  
  18.     public static void ShowWindow()  
  19.     {  
  20.         GetWindow<TaskPanel>("Task Panel");  
  21.     }  
  22.   
  23.     private void OnEnable()  
  24.     {  
  25.         // 初始化回调函数名称数组  
  26.         callbackFunctionNames = new[] { "Callback1", "Callback2", "Callback3", };  
  27.     }  
  28.   
  29.     private void OnGUI()  
  30.     {  
  31.         GUILayout.Label("Task Panel", EditorStyles.boldLabel);  
  32.   
  33.         taskName = EditorGUILayout.TextField("Task Name", taskName);  
  34.         time = EditorGUILayout.FloatField("Time", time);  
  35.         usingWorldTimeScale = EditorGUILayout.Toggle("Use World Time Scale", usingWorldTimeScale);  
  36.         isLoop = EditorGUILayout.Toggle("Is Loop", isLoop);  
  37.         isPause = EditorGUILayout.Toggle("Is Pause", isPause);  
  38.   
  39.         // 下拉菜单选择回调函数  
  40.         selectedCallbackIndex = EditorGUILayout.Popup("Callback Function", selectedCallbackIndex, callbackFunctionNames);  
  41.   
  42.         if (GUILayout.Button("Create Task"))  
  43.         {  
  44.             CreateTask();  
  45.         }  
  46.     }  
  47.   
  48.     private void CreateTask()  
  49.     {  
  50.         Action<Task> callback = null;  
  51.         if (selectedCallbackIndex >= 0 && selectedCallbackIndex < callbackFunctionNames.Length)  
  52.         {  
  53.             string callbackFunctionName = callbackFunctionNames[selectedCallbackIndex];  
  54.             callback = (Action<Task>)Delegate.CreateDelegate(typeof(Action<Task>), this, callbackFunctionName);  
  55.         }  
  56.   
  57.         // 这里假设 Schedule 是一个单例或者可以通过其他方式访问  
  58.         schedule = FindObjectOfType<Schedule>();  
  59.         if (schedule != null)  
  60.         {  
  61.             schedule.SetSchedule(taskName, time, callback, usingWorldTimeScale, isLoop, isPause);  
  62.         }  
  63.         else  
  64.         {  
  65.             Debug.LogError("Schedule object not found!");  
  66.         }  
  67.     }  
  68.   
  69.     // 示例回调函数  
  70.     public void Callback1(Task task)  
  71.     {  
  72.         Debug.Log("Callback1: Task " + task.TaskName + " completed!");  
  73.     }  
  74.   
  75.     public void Callback2(Task task)  
  76.     {  
  77.         Debug.Log("Callback2: Task " + task.TaskName + " completed!");  
  78.     }  
  79.   
  80.     public void Callback3(Task task)  
  81.     {  
  82.         Debug.Log("Callback3: Task " + task.TaskName + " completed!");  
  83.     }  
  84. }
复制代码
  1. const int FRAMES_PER_SECOND = 25;    //恒定的帧数
  2. const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;
  3. DWORD next_game_tick = GetTickCount();
  4. // GetTickCount() returns the current number of milliseconds
  5. // that have elapsed since the system was started
  6. int sleep_time = 0;
  7. bool game_is_running = true;
  8. while( game_is_running ) {
  9.       update_game();
  10.       display_game();
  11.       next_game_tick += SKIP_TICKS;
  12.       sleep_time = next_game_tick - GetTickCount();
  13.       if( sleep_time >= 0 ) {
  14.           Sleep( sleep_time );
  15.       }
  16.       else {
  17.           // Shit, we are running behind!
  18.       }
  19.   }
复制代码
  1.   DWORD prev_frame_tick;
  2.   DWORD curr_frame_tick = GetTickCount();
  3.   bool game_is_running = true;
  4.   while(game_is_running){
  5.       prev_frame_tick = curr_frame_tick;
  6.       curr_frame_tick = GetTickCount();
  7.       update_game(curr_frame_tick  -  prev_frame_tick);
  8.       display_game();
  9.   }
复制代码
责任链模式

***避免将一个请求的发送者与接收者耦合在一起,让多个对象都有机会处理请求。将接受者的对象连接成一条线,并且沿着这条链传递请求,知道有一个对象能够处理它为止
责任链模式(Chain of Responsibility Pattern)是一种行为型设计模式,它通过将多个处理器(处理对象)以链式结构连接起来,使得请求沿着这条链传递,直到有一个处理器处理该请求为止。这种模式的主要目的是解耦请求的发送者和接收者,使多个对象都有可能接收请求,而发送者不需要知道哪个对象会处理它
***应用场景

  • 多个对象可能处理同一个请求:当请求的处理不是固定的,或者需要动态决定哪个对象处理请求时。
  • 处理者对象集合需要动态确定:在运行时根据需要动态调整处理者顺序的场景。
  • 增强系统的灵活性:通过责任链模式,可以灵活地增加或移除责任链中的处理者。
***实现方式

  • Handler:定义一个处理请求的接口,包含一个设置下一个处理者的方法和一个处理请求的方法。
  • ConcreteHandler:Handler的实现对象,可以处理请求或将请求传递给链中的下一个处理者。
  • Client:创建处理者对象并设置它们之间的顺序。
***优点

  • 降低耦合度:责任链模式使得一个对象无须知道到底是哪一个对象处理其请求以及链的结构,发送者和接收者之间的耦合度降低。
  • 灵活性和可扩展性:通过责任链模式,可以动态地组合处理对象,灵活地配置处理流程,这种解耦使得系统更加灵活和可扩展
  1.   const int TICKS_PER_SECOND = 50;
  2.   const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
  3.   const int MAX_FRAMESKIP = 10;
  4.   DWORD next_game_tick = GetTickCount();
  5.   int loops;
  6.   bool game_is_running = true;
  7.   while( game_is_running ) {
  8.       loops = 0;
  9.       while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
  10.           update_game();
  11.           next_game_tick += SKIP_TICKS;
  12.           loops++;
  13.       }
  14.       display_game();
  15.   }
复制代码
组件模式

***组件模式(Component Pattern),它将一个大型的对象拆分成多个小型的组件,每个组件都有独立的职责和行为,并可以互相组合以构建出复杂系统。这种模式允许开发者将游戏中的各个功能模块(如主角状态模块、背包模块、装备模块、技能模块及战斗模块)独立开发和维护,从而提高代码的可重用性和可维护性。
***应用场景

  • 游戏开发和模拟中,其中游戏实体(如角色、物品)可以具有动态的能力或状态。
  • 需要高模块化的系统以及实体可能需要在运行时更改行为而无需继承层次结构的系统。
  • 当一个类越来越庞大,越来越难以开发时。
***数据结构

  • 组件类:定义了组件的接口和行为。
  • 组合类:将多个组件组合在一起,形成更复杂的对象。
***实现方式

  • 组件模式通过为图形和声音创建单独的组件类来解决复杂系统的问题,允许进行灵活和独立的开发。这种模块化方法增强了可维护性和可扩展性。
***优点

  • 灵活性和可复用性:组件可以在不同的实体中复用,使得添加新功能或修改现有功能更加容易。
  • 解耦:减少了游戏实体状态和行为之间的依赖关系,便于进行更改和维护。
  • 动态组合:实体可以通过添加或删除组件在运行时改变其行为,为游戏设计提供了极大的灵活性
  1.   const int TICKS_PER_SECOND = 25;
  2.   const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
  3.   const int MAX_FRAMESKIP = 5;
  4.   DWORD next_game_tick = GetTickCount();
  5.   int loops;
  6.   float interpolation;
  7.   bool game_is_running = true;
  8.   while( game_is_running ) {
  9.       loops = 0;
  10.       while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
  11.           update_game();
  12.           next_game_tick += SKIP_TICKS;
  13.           loops++;
  14.       }
  15.       interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
  16.                       / float( SKIP_TICKS );
  17.       display_game( interpolation );
  18.   }
复制代码
子类沙盒模式

***子类沙盒模式(SubClassSandbox)是一种设计思想,它通过在基类中定义一个抽象的沙盒方法和一些预定义的操作集合,来允许子类根据这些操作定义自己的行为。这些操作通常被设置为受保护的状态,以确保它们仅供子类使用
***应用场景

  • 你有一个带有大量子类的基类。
  • 基类能够提供所有子类可能需要执行的操作集合。
  • 在子类之间有重叠的代码,你希望在它们之间更简便地共享代码。
  • 你希望使这些继承类与程序其他代码之间的耦合最小化。
***实现方式

  • 在子类沙盒模式中,基类提供了一系列受保护的方法,这些方法被子类用来实现特定的行为。子类通过重写基类中的抽象沙盒方法来组合这些操作,从而实现自己的功能。
***优点

  • 减少耦合:通过将操作封装在基类中,子类之间的耦合被减少,因为每个子类仅与基类耦合。
  • 代码复用:子类可以复用基类提供的操作,减少了代码冗余。
  • 易于维护:当游戏系统的某部分改变时,修改基类即可,而不需要修改众多的子类。
***缺点

  • 脆弱的基类问题:由于子类通过基类接触游戏的剩余部分,基类最后和子类需要的每个系统耦合。这种蛛网耦合让你很难在不破坏什么的情况下改变基类
  1. public partial class Transform : Component, IEnumerable
  2. {
  3.     // 实现IEnumerable接口的GetEnumerator方法,返回一个枚举器用于遍历Transform的子对象。
  4.     public IEnumerator GetEnumerator()
  5.     {
  6.         return new Transform.Enumerator(this);
  7.     }
  8.     // 内部类Enumerator实现了IEnumerator接口,用于遍历Transform的子对象。
  9.     private class Enumerator : IEnumerator
  10.     {
  11.         // 引用外部的Transform实例,表示要遍历的父Transform。
  12.         Transform outer;
  13.         // 当前枚举到的索引,-1表示尚未开始或已结束。
  14.         int currentIndex = -1;
  15.         // 构造函数接收一个Transform实例作为参数,并初始化outer字段。
  16.         internal Enumerator(Transform outer)
  17.         {
  18.             this.outer = outer;
  19.         }
  20.         // 返回当前索引位置的子Transform对象。
  21.         public object Current
  22.         {
  23.             get { return outer.GetChild(currentIndex); }
  24.         }
  25.         // 移动到下一个元素,并返回是否成功移动到一个新的有效元素。
  26.         public bool MoveNext()
  27.         {
  28.             // 获取子对象的数量,并检查当前索引是否在范围内。
  29.             int childCount = outer.childCount;
  30.             return ++currentIndex < childCount;
  31.         }
  32.         // 重置枚举器的状态,将currentIndex设置为-1,表示回到起始状态。
  33.         public void Reset()
  34.         {
  35.             currentIndex = -1;
  36.         }
  37.     }
  38. }
复制代码
类型对象模式

***类型对象模式(Type Object Pattern)允许通过创建一个带有表示对象“类型”的字段的类来创建灵活且可重复使用的对象。这种设计模式对于在需要提前定义未定义的类型或需要修改或添加类型的场景非常有价值。它将部分类型系统从继承中抽离出来,放到可配置数据中
***应用场景

  • 当你需要定义不同“种”事物,但是语言自身的类型系统过于僵硬时。
  • 当你不知道后面还需要什么类型,或者想不改变代码或者重新编译就能修改或添加新类型时。
***实现方式

  • 类型对象模式通过定义类型对象类和有类型的对象类来实现。每个类型对象实例代表一种不同的逻辑类型。每种有类型的对象保存对描述它类型的类型对象的引用。实例相关的数据被存储在有类型对象的实例中,被同种类分享的数据或者行为存储在类型对象中。
***优点

  • 运行时创建新的类型对象:允许在运行时动态创建新的类型对象。
  • 避免子类膨胀:通过类型对象模式,可以避免子类的过度膨胀。
  • 客户程序无需了解实例与类型的分离:客户程序不需要了解实例与类型的分离。
  • 可以动态的更改类型:类型对象模式允许动态地更改类型
  1. namespace Iterator  
  2. {  
  3.   public interface IAggregate//IAggregate接口定义了创建相应迭代器的方法  
  4.   {  
  5.     void Add(object obj);  
  6.     void Remove(object obj);  
  7.     IIterator GetIterator();  
  8.   }  
  9. }
复制代码
命令队列模式

***命令队列模式(Command Queue Pattern)是用于管理和执行一系列命令。这种模式通常用于确保命令按特定顺序执行,并且一次只有一个命令在运行。它在游戏开发、事件处理系统和其他需要命令调度的场景中非常有用。
***应用场景

  • 当需要按特定顺序执行多个命令时。
  • 当需要确保一次只有一个命令在运行时。
  • 当需要一个灵活的命令调度机制时。
***实现方式

  • 命令队列模式通过定义命令接口(ICommand)、具体命令类、命令队列类(CommandQueue)和执行者(Invoker)来实现。每个具体命令类实现命令接口,包含执行命令的具体逻辑。命令队列类管理一个命令队列,确保命令按顺序执行。执行者负责将命令添加到队列中,并触发命令的执行。
***优点

  • 确保命令顺序执行:命令队列模式确保命令按特定顺序执行。
  • 避免并发执行问题:通过确保一次只有一个命令在运行,避免并发执行问题。
  • 提高系统的灵活性和可扩展性:命令队列模式提供了一种灵活且可扩展的命令调度机制。
  • 简化命令的管理和执行:通过集中管理命令的执行,简化了命令的管理和执行。
  1. namespace Iterator  
  2. {  
  3.   public interface IIterator//IIterator接口定义了遍历聚合对象所需的方法  
  4.   {  
  5.     object First();  
  6.     object Next();  
  7.     bool HasNext();  
  8.   }  
  9. }
复制代码
事件队列模式

***事件队列模式(Event Queue Pattern)是一种设计模式,用于管理和处理一系列事件。这种模式通常用于确保事件按特定顺序处理,并且可以异步地处理事件。它在图形用户界面(GUI)编程、游戏开发和其他需要事件驱动机制的场景中非常有用。
***应用场景

  • 当需要按特定顺序处理多个事件时。
  • 当需要异步处理事件,以避免阻塞主线程时。
  • 当需要一个灵活的事件处理机制时。
***实现方式

  • 事件队列模式通过定义事件接口、具体事件类、事件队列类(EventQueue)和事件处理器(EventHandler)来实现。每个具体事件类实现事件接口,包含事件的具体数据和处理逻辑。事件队列类管理一个事件队列,确保事件按顺序处理。事件处理器负责从队列中取出事件并处理。
***优点

  • 确保事件顺序处理:事件队列模式确保事件按特定顺序处理。
  • 支持异步事件处理:通过异步处理事件,避免阻塞主线程。
  • 提高系统的灵活性和可扩展性:事件队列模式提供了一种灵活且可扩展的事件处理机制。
  • 简化事件的管理和处理:通过集中管理事件的处理,简化了事件的管理和处理
  1. namespace Iterator  
  2. {  
  3.   public class ConcreteIterator : IIterator//ConcreteIterator 类实现了 IIterator 接口,提供了具体聚合对象的迭代逻辑  
  4.   {  
  5.     private List<object> _list = null;  
  6.     private int _index = -1;  
  7.   
  8.     public ConcreteIterator(List<object> list)  
  9.     {  
  10.       _list = list;  
  11.     }  
  12.   
  13.     public bool HasNext()  
  14.     {  
  15.       return _index < _list.Count - 1;  
  16.     }  
  17.   
  18.     public object First()  
  19.     {  
  20.       _index = 0;  
  21.       return _list[_index];  
  22.     }  
  23.   
  24.     public object Next()  
  25.     {  
  26.       if (HasNext())  
  27.       {  
  28.         _index++;  
  29.         return _list[_index];  
  30.       }  
  31.       return null;  
  32.     }  
  33.   }  
  34. }
复制代码
服务定位器模式

***服务定位器模式是一种设计模式,用于帮助应用程序查找和获取所需的服务对象。它提供了一种间接的方式来访问服务,将服务的具体创建和查找逻辑封装在一个中央定位器组件中。
***应用场景

  • 当应用程序需要以一种灵活且可维护的方式访问多个服务时。
  • 当需要解耦服务调用者和具体的服务实现时。
***实现方式

  • 服务定位器模式通过定义服务定位器接口、服务定位器实现、服务接口和具体服务来实现。服务定位器管理服务的注册和查找,客户端通过服务定位器来访问所需的服务。
***优点

  • 解耦服务访问:将服务访问逻辑与使用服务的业务逻辑分离。
  • 集中管理:服务的访问点集中管理,便于维护和扩展。
  • 灵活性:易于添加、修改或替换服务。
  • 延迟实例化:服务实例可以在首次请求时进行实例化(Lazy Instantiation),从而节省资源。
***缺点

  • 性能问题:服务定位器可能引入性能开销,特别是在每次服务请求都进行查找时。
  • 隐藏依赖:服务定位器通过全局访问点提供服务,可能导致依赖关系不清晰,使得代码的可读性和可测试性下降。
***使用建议

  • 考虑使用服务定位器模式时,应避免过度依赖服务定位器,因为它可能掩盖系统的依赖关系,使得调试和优化变得困难
  1. namespace Iterator  
  2. {  
  3.   public class ConcreteAggregate : IAggregate//ConcreteAggregate 类实现了 IAggregate 接口,封装了一个具体的聚合对象  
  4.   {  
  5.     private List<object> _list = new List<object>();  
  6.   
  7.     public void Add(object obj)  
  8.     {  
  9.       _list.Add(obj);  
  10.     }  
  11.   
  12.     public void Remove(object obj)  
  13.     {  
  14.       _list.Remove(obj);  
  15.     }  
  16.   
  17.     public IIterator GetIterator()  
  18.     {  
  19.       return new ConcreteIterator(_list);  
  20.     }  
  21.   }  
  22. }
复制代码
***另一种实现:
  1. namespace Iterator  
  2. {  
  3.   public class IteratorPatternDemo  
  4.   {  
  5.     static void Main(string[] args)  
  6.     {  
  7.       IAggregate aggregate = new ConcreteAggregate();  
  8.       aggregate.Add("中山大学");  
  9.       aggregate.Add("华南理工");  
  10.       aggregate.Add("韶关学院");  
  11.   
  12.       Console.WriteLine("聚合的内容有:");  
  13.       IIterator iterator = aggregate.GetIterator();  
  14.       while (iterator.HasNext())  
  15.       {  
  16.         object obj = iterator.Next();  
  17.         Console.Write(obj.ToString() + "\t");  
  18.       }  
  19.   
  20.       object firstObj = iterator.First();  
  21.       Console.WriteLine("\nFirst:" + firstObj.ToString());  
  22.     }  
  23.   }  
  24. }
复制代码
字节码模式

***应用场景

  • 当需要定义很多行为并且游戏的实现语言不合适时,请使用字节码模式,因为:

    • 它的等级太低,使得编程变得乏味或容易出错。

      • 字节码模式涉及将行为编码为虚拟机的指令,这些指令通常是非常底层的操作。这种底层操作可能会导致编程变得繁琐且容易出错,因为开发者需要处理大量的细节和低级操作

    • 由于编译时间慢或其他工具问题,迭代它需要很长时间。

      • 在游戏开发中,使用像C++这样的重型语言时,代码的每次更新都需要编译。由于代码量庞大,编译时间可能会很长。字节码模式通过将可变内容从核心代码中剥离出来,减少每次更改后需要重新编译的次数,从而缓解这个问题

    • 它有太多的信任。如果您想确保定义的行为不会破坏游戏,您需要将其与代码库的其余部分进行沙箱化。

      • 字节码模式定义的行为可能对游戏的其他部分有太多的依赖。为了确保这些行为不会破坏游戏,需要将它们与代码库的其余部分隔离开来,即进行沙箱化处理。这样可以防止行为的执行对游戏的其他部分产生不良影响


  1. public abstract class AbstractSkillHandler  
  2. {  
  3.     protected AbstractSkillHandler _nextSkill;  
  4.   
  5.     public AbstractSkillHandler(AbstractSkillHandler nextSkill)  
  6.     {  
  7.         _nextSkill = nextSkill;  
  8.     }  
  9.   
  10.     public abstract bool CanHandle(int energy);  
  11.   
  12.     public virtual void Handle(int energy)  
  13.     {  
  14.         _nextSkill?.Handle(energy); //如果下一个技能存在,则调用下一个Handle方法  
  15.     }  
  16. }
复制代码
***实现方式

  • 字节码模式通过定义一个虚拟机类来实现。虚拟机将指令作为输入并执行它们以提供游戏对象行为。它使用一个栈来管理操作数,并根据不同的指令执行不同的操作,如设置健康值、智慧值、敏捷值,播放声音和生成粒子等。
***优点

  • 高密度和线性执行:字节码是连续的二进制数据块,不会浪费任何一个字节。线性执行程度高,除了控制流跳转,其他的指令都是顺序执行的。
  • 底层执行:其执行指令是不可分割的,最简单的一个执行单元。
  1. using System;  
  2. using UnityEngine;  
  3.   
  4. namespace ComponentPattern  
  5. {  
  6.     public class Player : MonoBehaviour  
  7.     {  
  8.         private JumpComponent jumpComponent;  
  9.         private MoveComponent moveComponent;  
  10.   
  11.         private void Awake()  
  12.         {  
  13.             jumpComponent = gameObject.AddComponent<JumpComponent>();  
  14.             moveComponent = gameObject.AddComponent<MoveComponent>();  
  15.         }  
  16.   
  17.         private void Update()  
  18.         {  
  19.             if (Input.GetKeyDown(KeyCode.Space))  
  20.                 jumpComponent.Jump();  
  21.             if (Input.GetKey(KeyCode.A))  
  22.                 moveComponent.Move(false, 1);  
  23.             if (Input.GetKey(KeyCode.D))  
  24.                 moveComponent.Move(true, 1);  
  25.         }  
  26.     }  
  27. }
  28. using UnityEngine;  
  29.   
  30. namespace ComponentPattern  
  31. {  
  32.     public class MoveComponent : MonoBehaviour  
  33.     {  
  34.         public void Move(bool isRight, float speed)  
  35.         {  
  36.             float direction = isRight ? 1f : -1f;  
  37.             transform.Translate(Vector3.right * (direction * speed * Time.deltaTime), Space.World);  
  38.         }  
  39.     }  
  40. }
  41. using UnityEngine;  
  42.   
  43. namespace ComponentPattern  
  44. {  
  45.     public class JumpComponent : MonoBehaviour  
  46.     {  
  47.         public float JumpVelocity = 1f;  
  48.         public Rigidbody rb;  
  49.   
  50.         private void Start()  
  51.         {  
  52.             rb = gameObject.GetComponent<Rigidbody>();  
  53.         }  
  54.   
  55.         public void Jump()  
  56.         {  
  57.             rb.velocity = Vector3.up * JumpVelocity;  
  58.         }  
  59.     }  
  60. }
复制代码
脏标志

***脏标志通过使用一个布尔变量(脏标记),表示自上次处理或更新某个对象或资源以来,该对象或资源是否已被修改。当对对象进行更改时,该标记设置为“脏”(true),当对象被处理或更新时,设置为“干净”(false)
***应用场景

  • 计算和同步任务:脏标志模式主要应用在“计算”和“同步”两个任务中。适用于原始数据的变化速度远高于导出数据的使用速度,且增量更新十分困难的情况。
  • 性能优化:只在性能问题足够大时,再使用这一模式增加代码的复杂度。脏标志在两种任务上应用:“计算”和“同步”。
  • 避免不必要的工作:将工作推迟到必要时进行,以避免不必要的工作。
***注意事项

  • 脏标记的设置和清除:每次状态的改变就必须设置标识,在项目中要统一修改数据的接口。得到之前的推导数据保存在内存中,这个模式需要内存中保存推导数据,以防在使用。以空间换时间。
  • 避免卡顿:延期到需要结果的时候执行,但是当这个工作本身就很耗时,就会造成卡顿。
  1. using UnityEngine;  
  2.   
  3. namespace SubclassSandboxPattern  
  4. {  
  5.     public class GameController : MonoBehaviour  
  6.     {  
  7.         private SkyLaunch skyLaunch;  
  8.         private SpeedLaunch speedLaunch;  
  9.   
  10.         private void Start()  
  11.         {  
  12.             skyLaunch = new SkyLaunch();  
  13.             speedLaunch = new SpeedLaunch();  
  14.         }  
  15.   
  16.         private void Update() //可以结合状态模式来控制超级能力是否可以使用  
  17.         {  
  18.             if (Input.GetKeyDown(KeyCode.Space))  
  19.             {  
  20.                 skyLaunch.Activate();  
  21.             }  
  22.   
  23.             if (Input.GetKeyDown(KeyCode.S))  
  24.             {  
  25.                 speedLaunch.Activate();  
  26.             }  
  27.         }  
  28.     }  
  29. }
  30. using UnityEngine;  
  31.   
  32. namespace SubclassSandboxPattern  
  33. {  
  34.     // Superpower 抽象类是所有超级能力的基础  
  35.     public abstract class Superpower  
  36.     {  
  37.         // 子类必须实现这个方法,它表示激活超级能力时的行为  
  38.         public abstract void Activate();  
  39.   
  40.         protected void Move(string where)  
  41.         {  
  42.             Debug.Log($"Moving towards {where}");  
  43.         }  
  44.   
  45.         protected void PlaySound(string sound)  
  46.         {  
  47.             Debug.Log($"Playing sound {sound}");  
  48.         }  
  49.   
  50.         protected void SpawnParticles(string particles)  
  51.         {  
  52.             Debug.Log($"Firing {particles}");  
  53.         }  
  54.     }  
  55. }
  56. namespace SubclassSandboxPattern  
  57. {  
  58.     public class SkyLaunch : Superpower  
  59.     {  
  60.         // 重写父类的 Activate 方法,定义当 SkyLaunch 被激活时的行为。  
  61.         public override void Activate()  
  62.         {  
  63.             PlaySound("Launch Sky sound"); // 播放发射声音  
  64.             SpawnParticles("Fly"); // 生成尘埃粒子效果  
  65.             Move("sky"); // 移动到天空  
  66.         }  
  67.     }  
  68. }
  69. namespace SubclassSandboxPattern  
  70. {  
  71.     public class SpeedLaunch : Superpower  
  72.     {  
  73.         public override void Activate()  
  74.         {  
  75.             PlaySound("Launch Speed Launch");  
  76.             SpawnParticles("dust");  
  77.             Move("quickly");  
  78.         }  
  79.     }  
  80. }
复制代码
对象池

***对象池(Object Pool Pattern)是一种创建型设计模式,它用于管理和复用一组预先创建的对象。这种模式的主要目的是为了提高性能和节省资源,尤其适用于创建对象成本较高,而对象使用频繁的场景。
***应用场景:

  • 当应用程序需要频繁创建和销毁对象,且对象的创建成本较高时。
  • 当需要限制资源的使用,如数据库连接或网络连接时。
  • 在内存中数量受限的对象,如线程或数据库连接。
***实现方式:

  • 对象池模式通过定义一个对象池管理器来实现,该管理器负责对象的创建、存储、分配和回收。
  • 对象池管理器预先创建一定数量的对象,并在池中维护这些对象。
  • 当需要对象时,可以从池中获取一个对象;使用完毕后,将对象归还到池中,而不是销毁。
***优点:

  • 资源复用:减少对象创建和销毁的开销,尤其适用于创建成本高的对象。
  • 性能优化:通过减少对象创建和垃圾回收的时间来提高应用性能。
  • 管理便利性:集中管理对象的生命周期,可以灵活控制资源的使用。
[unity三种对象池实现(simple,optimized,unityNative)](file:///D:/StudyProject/unity/GameDesignPattern_U3D_Version/Assets/ObjectPool)
单独的对象池类实现:
Simple:
  1. using UnityEngine;  
  2.   
  3. namespace TypeObjectController  
  4. {  
  5.     public class TypeObjectController : MonoBehaviour  
  6.     {  
  7.         private void Start()  
  8.         {  
  9.             // 创建各种动物实例,并设置它们是否能飞。  
  10.             Bird ostrich = new Bird("ostrich", canFly: false);  
  11.             Bird pigeon = new Bird("pigeon", canFly: true);  
  12.             Mammal rat = new Mammal("rat", canFly: false);  
  13.             Mammal bat = new Mammal("bat", canFly: true);  
  14.             Fish flyingFish = new Fish("flying fish", canFly: true);  
  15.             Fish goldFish = new Fish("goldfish", canFly: false);  
  16.   
  17.             // 调用 Talk 方法来输出每种动物是否能飞的信息。  
  18.             ostrich.Talk();  
  19.             pigeon.Talk();  
  20.             rat.Talk();  
  21.             bat.Talk();  
  22.             flyingFish.Talk();  
  23.             goldFish.Talk();  
  24.         }  
  25.     }  
  26. }
  27. namespace TypeObjectController  
  28. {  
  29.     //定义了一个可以飞行的类型的契约,任何实现了此接口的类都需要提供 CanIFly() 方法的实现,该方法返回布尔值以表示该类型是否能够飞行  
  30.     public interface IFlyingType  
  31.     {  
  32.         bool CanIFly();  
  33.     }  
  34. }
  35. namespace TypeObjectController  
  36. {  
  37.     //实现了 IFlyingType 接口的具体类,分别代表了能飞和不能飞的类型  
  38.     public class ICanFly : IFlyingType  
  39.     {  
  40.         public bool CanIFly()  
  41.         {  
  42.             return true;  
  43.         }  
  44.     }  
  45.   
  46.     public class ICantFly : IFlyingType  
  47.     {  
  48.         public bool CanIFly()  
  49.         {  
  50.             return false;  
  51.         }  
  52.     }  
  53. }
  54. namespace TypeObjectController  
  55. {  
  56.     public abstract class Animal  
  57.     {  
  58.         protected string name;  
  59.         protected IFlyingType flyingType;  
  60.   
  61.         protected Animal(string name, bool canFly)  
  62.         {  
  63.             this.name = name;  
  64.             flyingType = canFly ? new ICanFly() : new ICantFly();  
  65.         }  
  66.   
  67.         public abstract void Talk();  
  68.     }  
  69. }
  70. using UnityEngine;  
  71.   
  72. namespace TypeObjectController  
  73. {  
  74.     public class Bird : Animal  
  75.     {  
  76.         public Bird(string name, bool canFly) : base(name, canFly) { }  
  77.   
  78.         public override void Talk()  
  79.         {  
  80.             string canFlyString = flyingType.CanIFly() ? "can" : "can't";  
  81.             Debug.Log($"Hello this is {name}, I'm a bird, and I {canFlyString} fly!");  
  82.         }  
  83.     }  
  84. }
  85. using UnityEngine;  
  86.   
  87. namespace TypeObjectController  
  88. {  
  89.     public class Mammal : Animal  
  90.     {  
  91.         public Mammal(string name, bool canFly) : base(name, canFly) { }  
  92.   
  93.         public override void Talk()  
  94.         {  
  95.             string canFlyString = flyingType.CanIFly() ? "can" : "can't";  
  96.   
  97.             Debug.Log($"Hello this is {name}, I'm a mammal, and I {canFlyString} fly!");  
  98.         }  
  99.     }  
  100. }
  101. using UnityEngine;  
  102.   
  103. namespace TypeObjectController  
  104. {  
  105.     public class Fish : Animal  
  106.     {  
  107.         public Fish(string name, bool canFly) : base(name, canFly) { }  
  108.   
  109.         public override void Talk()  
  110.         {  
  111.             string canFlyString = flyingType.CanIFly() ? "can" : "can't";  
  112.   
  113.             Debug.Log($"Hello this is {name}, I'm a fish, and I {canFlyString} fly!");  
  114.         }  
  115.     }  
  116. }
复制代码
Optimized:
  1. using UnityEngine;  
  2.   
  3. namespace DecouplingPatterns.CommandQueue  
  4. {  
  5.     public class GameController : MonoBehaviour  
  6.     {  
  7.         public Popup firstPopUp, secondPopup, thirdPopup;  
  8.   
  9.         private CommandQueue _commandQueue;  
  10.   
  11.         private void Start()  
  12.         {  
  13.             // create a command queue  
  14.             _commandQueue = new CommandQueue();  
  15.             StartCommands();  
  16.         }  
  17.   
  18.         public void StartCommands()  
  19.         {  
  20.             _commandQueue.Clear();  
  21.             // add commands  
  22.             _commandQueue.Enqueue(new FirstCmd(this));  
  23.             _commandQueue.Enqueue(new SecondCmd(this));  
  24.             _commandQueue.Enqueue(new ThirdCmd(this));  
  25.             Debug.Log("Commands enqueued");  
  26.         }  
  27.     }  
  28. }
  29. using System.Collections.Generic;  
  30.   
  31. namespace DecouplingPatterns.CommandQueue  
  32. {  
  33.     //该类管理一个命令队列,确保命令按顺序执行,并且一次只有一个命令正在运行  
  34.     public class CommandQueue  
  35.     {  
  36.         private readonly Queue<ICommand> _queue;  
  37.         public bool _isPending; // it's true when a command is running  
  38.   
  39.         public CommandQueue()  
  40.         {  
  41.             _queue = new Queue<ICommand>();  
  42.             _isPending = false;  
  43.         }  
  44.   
  45.         public void Enqueue(ICommand cmd)  
  46.         {  
  47.             _queue.Enqueue(cmd);  
  48.   
  49.             if (!_isPending) // if no command is running, start to execute commands  
  50.                 DoNext();  
  51.         }  
  52.   
  53.         public void DoNext()  
  54.         {  
  55.             if (_queue.Count == 0)  
  56.                 return;  
  57.   
  58.             ICommand cmd = _queue.Dequeue();  
  59.             // setting _isPending to true means this command is running  
  60.             _isPending = true;  
  61.             // listen to the OnFinished event  
  62.             cmd.OnFinished += OnCmdFinished;  
  63.             cmd.Execute();  
  64.         }  
  65.   
  66.         private void OnCmdFinished()  
  67.         {  
  68.             // current command is finished  
  69.             _isPending = false;  
  70.             // run the next command  
  71.             DoNext();  
  72.         }  
  73.   
  74.         public void Clear()  
  75.         {  
  76.             _queue.Clear();  
  77.             _isPending = false;  
  78.         }  
  79.     }  
  80. }
  81. using System;  
  82.   
  83. namespace DecouplingPatterns.CommandQueue  
  84. {  
  85.     // The command interface defines the methods that all commands must implement  
  86.     public interface ICommand  
  87.     {  
  88.         Action OnFinished { get; set; }  
  89.   
  90.         void Execute();  
  91.     }  
  92. }
  93. using System;  
  94. using UnityEngine;  
  95.   
  96. namespace DecouplingPatterns.CommandQueue  
  97. {  
  98.     //Represents a user interface component that can be displayed and closed  
  99.     public class Popup : MonoBehaviour  
  100.     {  
  101.         public Action onClose;  
  102.   
  103.         public void Close()  
  104.         {  
  105.             onClose?.Invoke();  
  106.         }  
  107.     }  
  108. }
  109. using System;  
  110.   
  111. namespace DecouplingPatterns.CommandQueue  
  112. {  
  113.     public class BaseCommand : ICommand  
  114.     {  
  115.         public Action OnFinished { get; set; }  
  116.         protected readonly GameController _owner;  
  117.   
  118.         protected BaseCommand(GameController owner)  
  119.         {  
  120.             _owner = owner;  
  121.         }  
  122.   
  123.         public virtual void Execute() { }  
  124.   
  125.         protected virtual void OnClose() { }  
  126.     }  
  127. }
  128. using UnityEngine;  
  129.   
  130. namespace DecouplingPatterns.CommandQueue  
  131. {  
  132.     public class FirstCmd : BaseCommand  
  133.     {  
  134.         public FirstCmd(GameController owner) : base(owner) { }  
  135.   
  136.         public override void Execute()  
  137.         {  
  138.             _owner.firstPopUp.gameObject.SetActive(true); //Activate the first pop-up window and subscribe to its closing event  
  139.             _owner.firstPopUp.onClose += OnClose;  
  140.             Debug.Log("Executing First Command");  
  141.         }  
  142.   
  143.         protected override void OnClose()  
  144.         {  
  145.             _owner.firstPopUp.onClose -= OnClose; //Remove subscriptions to close events to prevent memory leaks  
  146.             _owner.firstPopUp.gameObject.SetActive(false);  
  147.             OnFinished?.Invoke();  
  148.             Debug.Log("First Command Finished");  
  149.         }  
  150.     }  
  151. }
  152. using UnityEngine;  
  153.   
  154. namespace DecouplingPatterns.CommandQueue  
  155. {  
  156.     public class SecondCmd : BaseCommand  
  157.     {  
  158.         public SecondCmd(GameController owner) : base(owner) { }  
  159.   
  160.         public override void Execute()  
  161.         {  
  162.             _owner.secondPopup.gameObject.SetActive(true);  
  163.             _owner.secondPopup.onClose += OnClose;  
  164.             Debug.Log("Second command executed");  
  165.         }  
  166.   
  167.         protected override void OnClose()  
  168.         {  
  169.             _owner.secondPopup.onClose -= OnClose;  
  170.             _owner.secondPopup.gameObject.SetActive(false);  
  171.             OnFinished?.Invoke();  
  172.             Debug.Log("Second command finished");  
  173.         }  
  174.     }  
  175. }
  176. using UnityEngine;  
  177.   
  178. namespace DecouplingPatterns.CommandQueue  
  179. {  
  180.     public class ThirdCmd : BaseCommand  
  181.     {  
  182.         public ThirdCmd(GameController owner) : base(owner) { }  
  183.   
  184.         public override void Execute()  
  185.         {  
  186.             _owner.thirdPopup.gameObject.SetActive(true);  
  187.             _owner.thirdPopup.onClose += OnClose;  
  188.             Debug.Log("Third command executed");  
  189.         }  
  190.   
  191.         protected override void OnClose()  
  192.         {  
  193.             _owner.thirdPopup.onClose -= OnClose;  
  194.             _owner.thirdPopup.gameObject.SetActive(false);  
  195.             OnFinished?.Invoke();  
  196.             Debug.Log("Third command finished");  
  197.         }  
  198.     }  
  199. }
复制代码
Unity自带:
  1. namespace DecouplingPatterns.EventQueue  
  2. {  
  3.     using System.Collections.Generic;  
  4.     using UnityEngine;  
  5.   
  6.     public class EventQueue : MonoBehaviour  
  7.     {  
  8.         public GameObject PosIndicator;  
  9.         public Holder Holder;  
  10.         private Queue<Transform> _destinationQueue;  
  11.         private Transform _destination;  
  12.         public float Speed = 10;  
  13.   
  14.         private void Start()  
  15.         {  
  16.             MouseInputManager.Instance.OnMouseClick += AddDestination;  
  17.             _destinationQueue = new Queue<Transform>();  
  18.         }  
  19.   
  20.         private void OnDestroy()  
  21.         {  
  22.             MouseInputManager.Instance.OnMouseClick -= AddDestination;  
  23.         }  
  24.   
  25.         private void AddDestination()  
  26.         {  
  27.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //将屏幕坐标转换为世界坐标射线  
  28.             /*  
  29.              *? 在三维空间中,射线是一个从某个起点开始并沿着某个方向无限延伸的线。Unity 中的Ray 结构体有两个主要属性:  
  30.              *? origin:射线的起点,通常是一个三维坐标 (x, y, z)             *? direction:射线的方向,也是一个三维向量,表示射线延伸的方向  
  31.              *? GetPoint(float distance)方法接受一个浮点数参数,它指定了从射线起点出发的距离。该方法会计算并返回射线上距离起点distance单位长度的那个点的坐标  
  32.              * GetPoint(10)返回的是距离射线起点(即相机位置)10 个单位远的点。这意味着无论在屏幕上哪里点击,都会得到一个与相机保持固定距离的新位置作为目的地  
  33.              * 择 10 个单位作为一个固定值是为了确保生成的目的地不会太近或太远  
  34.              * 如果距离设置得太小,可能会导致目标点出现在相机前非常靠近的地方;  
  35.              * 而如果太大,则可能使目标点超出合理范围或难以控制。  
  36.              */            Vector3 destination = ray.GetPoint(10);  
  37.             GameObject indicator = Instantiate(PosIndicator, destination, Quaternion.identity);  
  38.             _destinationQueue.Enqueue(indicator.transform);  
  39.         }  
  40.   
  41.         private void Update()  
  42.         {  
  43.             if (_destination == null && _destinationQueue.Count > 0)  
  44.             {  
  45.                 _destination = _destinationQueue.Dequeue();  
  46.             }  
  47.   
  48.             if (_destination == null) return;  
  49.   
  50.             Vector3 startPosition = Holder.transform.position;  
  51.             Vector3 destinationPosition = _destination.position;  
  52.   
  53.             float distance = Vector3.Distance(startPosition, destinationPosition); //计算当前位置与目标位置之间的距离  
  54.             //使用 Lerp 方法平滑地向目标位置移动  
  55.             startPosition = Vector3.Lerp(startPosition, destinationPosition, Mathf.Clamp01((Time.deltaTime * Speed) / distance));  
  56.             Holder.transform.position = startPosition;  
  57.             Holder.ExecuteEvent(destinationPosition);  
  58.   
  59.             if (distance < 0.01f)  
  60.             {  
  61.                 Destroy(_destination.gameObject);  
  62.                 _destination = null;  
  63.             }  
  64.         }  
  65.     }  
  66. }
  67. using UnityEngine;  
  68.   
  69. namespace DecouplingPatterns.EventQueue  
  70. {  
  71.     public interface IHolder  
  72.     {  
  73.         public void ExecuteEvent(Vector3 targetPos);  
  74.     }  
  75. }
  76. using UnityEngine;  
  77.   
  78. namespace DecouplingPatterns.EventQueue  
  79. {  
  80.     public class Holder : MonoBehaviour, IHolder  
  81.     {  
  82.         public virtual void ExecuteEvent(Vector3 targetPos) { }  
  83.     }  
  84. }
  85. using UnityEngine;  
  86.   
  87. public class MouseInputManager : MonoBehaviour  
  88. {  
  89.     public delegate void MouseInputeHandler();  
  90.     public MouseInputeHandler OnMouseClick;  
  91.     public static MouseInputManager Instance;  
  92.   
  93.     private void Awake()  
  94.     {  
  95.         Instance = this;  
  96.     }  
  97.   
  98.     private void Update()  
  99.     {  
  100.         if (Input.GetMouseButtonDown(0))  
  101.         {  
  102.             OnMouseClick();  
  103.         }  
  104.     }  
  105. }
  106. using UnityEngine;  
  107.   
  108. namespace DecouplingPatterns.EventQueue  
  109. {  
  110.     public class Dragon : Holder  
  111.     {  
  112.         public override void ExecuteEvent(Vector3 targetPos)  
  113.         {  
  114.             Vector3 direction = targetPos - transform.position; // 计算方向向量  
  115.             Quaternion targetRotation = Quaternion.LookRotation(direction); // 计算旋转角度  
  116.             transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 5f);  
  117.         }  
  118.     }  
  119. }
复制代码
空间分区模式

***空间分区模式(Spatial Partition Pattern)是一种优化模式,它通过将空间划分为不重叠的区域来有效地管理和查询空间数据。这种模式在计算机图形学、游戏开发和地理信息系统中被广泛使用,特别是用于优化诸如碰撞检测、射线投射和最近邻搜索等操作。
***应用场景

  • 当需要高效地定位和访问空间中的对象时。
  • 在游戏开发中,用于管理游戏对象,如敌人、子弹、障碍物等。
  • 在计算机图形学中,用于快速确定哪些对象需要渲染。
***实现方式

  • 固定网格:将空间划分为固定大小的网格,每个网格存储该区域内的对象。
  • 四叉树:递归地将空间划分为四个象限,直到满足特定条件(如对象数量)。
  • k-d树:在每个维度上递归地划分空间,适用于多维数据的快速检索。
  • BSP树:类似于四叉树,但用于三维空间,常用于游戏开发中的可见性判断。
***优点

  • 提高效率:通过减少需要检查的对象数量来提高查询效率。
  • 简化查询:使得空间查询更加直观和易于实现。
  • 优化性能:通过减少计算量来提升性能。
***缺点

  • 内存使用:可能需要额外的内存来存储空间数据结构。
  • 更新开销:当对象移动时,需要更新空间数据结构。
  • 实现复杂性:对于动态变化的空间数据,实现可能较为复杂。
***使用建议

  • 在对象数量较多且需要频繁进行空间查询的场景下使用。
  • 根据应用场景选择合适的空间数据结构,如固定网格适合静态场景,四叉树适合动态变化的场景。
  • 注意平衡内存使用和查询效率,避免过度优化导致资源浪费。
  1. using UnityEngine;  
  2.   
  3. namespace ServiceLocatorPatterns.AudioServiceLocator  
  4. {  
  5.     public class GameController : MonoBehaviour  
  6.     {  
  7.         private void Start()  
  8.         {  
  9.             // 创建一个 ConsoleAudio 实例,并通过 Locator 注册该实例作为当前游戏的音频服务提供者。  
  10.             // 如果希望禁用音频功能,可以传递 null 给 Provide 方法。  
  11.             var consoleAudio = new ConsoleAudio();  
  12.             Locator.Provide(consoleAudio);  
  13.             //Locator.Provide(null); // 用于测试 NullAudio 的行为  
  14.         }  
  15.   
  16.         private void Update()  
  17.         {  
  18.             // 从 Locator 获取当前的音频服务提供者。  
  19.             Audio locatorAudio = Locator.GetAudio();  
  20.   
  21.             if (Input.GetKeyDown(KeyCode.P))  
  22.             {  
  23.                 locatorAudio.PlaySound(23);  
  24.             }  
  25.             else if (Input.GetKeyDown(KeyCode.S))  
  26.             {  
  27.                 locatorAudio.StopSound(23);  
  28.             }  
  29.             else if (Input.GetKeyDown(KeyCode.Space))  
  30.             {  
  31.                 locatorAudio.StopAllSounds();  
  32.             }  
  33.         }  
  34.     }  
  35. }
  36. namespace ServiceLocatorPatterns.AudioServiceLocator  
  37. {  
  38.     // 定义了一个抽象类 Audio,规定所有音频服务必须实现的方法  
  39.     public abstract class Audio  
  40.     {  
  41.         public abstract void PlaySound(int soundID);  
  42.         public abstract void StopSound(int soundID);  
  43.         public abstract void StopAllSounds();  
  44.     }  
  45. }
  46. namespace ServiceLocatorPatterns.AudioServiceLocator  
  47. {  
  48.     //作为服务定位器,负责持有当前活动的 Audio 服务实例  
  49.     public class Locator  
  50.     {  
  51.         private static NullAudio nullService;  
  52.         private static Audio service;  
  53.   
  54.         // 静态构造函数,确保在第一次访问 Locator 类之前初始化默认的服务实例  
  55.         static Locator()  
  56.         {  
  57.             nullService = new NullAudio();  
  58.             // 初始化时设置为 nullService,以防止忘记注册实际的 Audio 实现  
  59.             service = nullService;  
  60.         }  
  61.   
  62.         // 返回当前注册的音频服务实例  
  63.         public static Audio GetAudio()  
  64.         {  
  65.             return service;  
  66.         }  
  67.   
  68.         // 允许外部代码通过此方法注册或替换当前的音频服务实例  
  69.         public static void Provide(Audio _service)  
  70.         {  
  71.             // 如果传入 null,则使用 nullService 来代替,这通常用于禁用音频功能  
  72.             service = _service ?? nullService;  
  73.         }  
  74.     }  
  75. }
  76. using UnityEngine;  
  77.   
  78. namespace ServiceLocatorPatterns.AudioServiceLocator  
  79. {  
  80.     public class ConsoleAudio : Audio  
  81.     {  
  82.         // 在控制台输出一条信息表示开始播放指定 ID 的声音。  
  83.         public override void PlaySound(int soundID)  
  84.         {  
  85.             Debug.Log($"Sound {soundID} has started");  
  86.         }  
  87.   
  88.         // 在控制台输出一条信息表示停止播放指定 ID 的声音。  
  89.         public override void StopSound(int soundID)  
  90.         {  
  91.             Debug.Log($"Sound {soundID} has stopped");  
  92.         }  
  93.   
  94.         // 在控制台输出一条信息表示停止所有正在播放的声音。  
  95.         public override void StopAllSounds()  
  96.         {  
  97.             Debug.Log("All sounds have stopped");  
  98.         }  
  99.     }  
  100. }
  101. using UnityEngine;  
  102.   
  103. namespace ServiceLocatorPatterns.AudioServiceLocator  
  104. {  
  105.     // NullAudio 类提供了不执行任何操作的音频服务实现。  
  106.     // 这种设计允许系统在缺少有效音频服务时不会崩溃,而是可以优雅地忽略所有的音频请求。  
  107.     public class NullAudio : Audio  
  108.     {  
  109.         public override void PlaySound(int soundID)  
  110.         {  
  111.             Debug.Log("Do nothing - PlaySound");  
  112.         }  
  113.   
  114.         public override void StopSound(int soundID)  
  115.         {  
  116.             Debug.Log("Do nothing - StopSound");  
  117.         }  
  118.   
  119.         public override void StopAllSounds()  
  120.         {  
  121.             Debug.Log("Do nothing - StopAllSounds");  
  122.         }  
  123.     }  
  124. }
复制代码
装饰模式

***装饰模式(Decorator Pattern)允许在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式。它通过创建一个包装对象(即装饰器)来包裹真实的对象,从而在运行时根据需要动态地添加或撤销功能。
***应用场景

  • 动态扩展功能:当需要在运行时决定是否给对象添加额外的行为时,装饰模式非常适合。例如,在系统中根据用户的权限级别动态地赋予不同的访问权限。
  • 灵活组合对象行为:装饰模式允许通过组合不同的装饰器来给对象添加多种行为。这使得可以根据需要构造出各种各样的行为组合,满足不同的业务需求。
  • 避免类爆炸:当使用继承来扩展对象功能时,可能会导致类数量的急剧增加(即类爆炸)。而装饰模式提供了一种替代方案,通过组合而不是继承来扩展功能,从而简化了类结构。
***优点

  • 动态扩展:可以在运行时动态地添加或撤销对象的职责,而不需要修改对象的代码。
  • 灵活性:可以自由地组合和排列不同的装饰器,以创建出各种定制化的对象。
  • 简化类结构:通过使用装饰模式,可以避免为了支持各种组合而创建大量的子类。
***缺点

  • 装饰模式增加了许多小类,如果过度使用会使程序变得很复杂。
  • 不易调试:由于装饰器模式涉及到多个对象的交互,调试可能会变得相对困难。特别是当装饰器链很长时,追踪请求和响应的路径可能会变得复杂
  1. using System;  
  2. using System.Collections.Concurrent;  
  3. using UnityEngine;  
  4.   
  5. namespace ServiceLocatorPatterns.AnotherImplementation  
  6. {  
  7.     // 服务定位器类,使用静态上下文来存储已经注册的对象,并允许从任何地方解析(获取)这些对象。  
  8.     public static class ServiceLocator  
  9.     {  
  10.         // 使用 ConcurrentDictionary 来存储已注册的服务实例,确保线程安全和高效查找。  
  11.         private static readonly ConcurrentDictionary<Type, object> _registeredServices;  
  12.   
  13.         // 静态构造函数,在第一次使用该类的静态成员或创建该类的第一个实例之前自动执行,不需要显式地调用静态构造函数  
  14.         static ServiceLocator()  
  15.         {  
  16.             _registeredServices = new ConcurrentDictionary<Type, object>();  
  17.         }  
  18.   
  19.         // Register 方法用来向服务定位器中注册一个服务实例。  
  20.         // T 是泛型类型参数,限定只能是 class 类型。  
  21.         public static bool Register<T>(T service) where T : class  
  22.         {  
  23.             try  
  24.             {  
  25.                 if (_registeredServices.ContainsKey(typeof(T)))  
  26.                     throw new Exception($"ServiceLocator: {typeof(T)} has already been registered."); // 已经注册过该类型,抛出异常  
  27.                 _registeredServices[typeof(T)] = service;  
  28.                 Debug.Log($"ServiceLocator: Registered {typeof(T)}");  
  29.                 return true;  
  30.             } catch (Exception e)  
  31.             {  
  32.                 Debug.LogError($"ServiceLocator: Failed to register {typeof(T)}: {e.Message}");  
  33.                 return false;  
  34.             }  
  35.         }  
  36.   
  37.         // Unregister 方法从服务定位器中注销一个具体的服务实例。  
  38.         // 如果该实例不再需要或对象被销毁时调用。  
  39.         public static bool Unregister<T>(T instance) where T : class  
  40.         {  
  41.             if (!_registeredServices.TryGetValue(typeof(T), out object obj)) return false;  
  42.             if (!ReferenceEquals(obj, instance)) return false; //比较两个引用类型的对象是否指向同一个内存地址。对于引用类型来说,这意味着它们实际上是指向同一个对象实例  
  43.             if (!_registeredServices.TryRemove(typeof(T), out _)) return false;  
  44.   
  45.             Debug.Log($"ServiceLocator: Unregistered {typeof(T)}");  
  46.             return true;  
  47.         }  
  48.   
  49.         // Resolve 方法尝试解析指定类型的服务实例。  
  50.         // 如果找到则返回该实例,否则返回 null。  
  51.         public static T Resolve<T>() where T : class  
  52.         {  
  53.             if (_registeredServices.TryGetValue(typeof(T), out object obj))  
  54.             {  
  55.                 return (T)obj;  
  56.             }  
  57.   
  58.             return null;  
  59.         }  
  60.     }  
  61. }
  62. using UnityEngine;  
  63.   
  64. namespace ServiceLocatorPatterns.AnotherImplementation  
  65. {  
  66.     public class GameController : MonoBehaviour  
  67.     {  
  68.         private void Start()  
  69.         {  
  70.             var firstService = ServiceLocator.Resolve<FirstService>();  
  71.             var secondService = ServiceLocator.Resolve<SecondService>();  
  72.             var thirdService = ServiceLocator.Resolve<ThirdService>();  
  73.   
  74.             if (firstService != null)  
  75.             {  
  76.                 firstService.SayHi();  
  77.             }  
  78.   
  79.             if (secondService != null)  
  80.             {  
  81.                 secondService.SimpleMethod();  
  82.             }  
  83.   
  84.             if (thirdService != null)  
  85.             {  
  86.                 thirdService.Foo();  
  87.             }  
  88.   
  89.             ServiceLocator.Unregister(firstService);  
  90.             ServiceLocator.Unregister(secondService);  
  91.             ServiceLocator.Unregister(thirdService);  
  92.         }  
  93.     }  
  94. }
  95. using UnityEngine;  
  96.   
  97. namespace ServiceLocatorPatterns.AnotherImplementation  
  98. {  
  99.     public class FirstService : MonoBehaviour  
  100.     {  
  101.         private void Awake()  
  102.         {  
  103.             ServiceLocator.Register(this);  
  104.             //ServiceLocator.Register(this);//抛出异常,因为已经注册过了  
  105.         }  
  106.   
  107.         private void OnDestroy()  
  108.         {  
  109.             ServiceLocator.Unregister(this);  
  110.         }  
  111.   
  112.         public void SayHi()  
  113.         {  
  114.             Debug.Log("Hi, this is the " + nameof(FirstService));  
  115.         }  
  116.     }  
  117. }
  118. using UnityEngine;  
  119.   
  120. namespace ServiceLocatorPatterns.AnotherImplementation  
  121. {  
  122.     public class SecondService : MonoBehaviour  
  123.     {  
  124.         private void Awake()  
  125.         {  
  126.             ServiceLocator.Register(this);  
  127.         }  
  128.   
  129.         private void OnDestroy()  
  130.         {  
  131.             ServiceLocator.Unregister(this);  
  132.         }  
  133.   
  134.         public void SimpleMethod()  
  135.         {  
  136.             Debug.Log("Hey, this is just a simple method from " + nameof(SecondService));  
  137.         }  
  138.     }  
  139. }
复制代码
工厂模式

***工厂模式(Factory Pattern)是一种创建型设计模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。工厂模式可以分为以下几种:

  • 简单工厂模式(Simple Factory Pattern)
    简单工厂模式不是一个正式的设计模式,它只是通过一个工厂类来创建对象,但不涉及接口或抽象类。它通常包含一个工厂方法,根据输入参数返回不同的对象实例。
  • 工厂方法模式(Factory Method Pattern)
    工厂方法模式定义了一个创建对象的接口,但允许子类改变实例化的类型。工厂方法让类把实例化推迟到子类。
  • 抽象工厂模式(Abstract Factory Pattern)
    抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而不需要指定它们的具体类。抽象工厂模式强调一系列相关对象的创建,而不是单个对象。
***应用场景

  • 当一个类不知道它所必须创建的对象的类的时候。
  • 当一个类希望其子类来指定它所创建的对象的时候。
  • 当创建复杂对象时,需要保证对象的一致性或复用性时。
***优点

  • 单一职责原则:工厂模式将对象的创建和使用分离,降低了系统的复杂度。
  • 开闭原则:系统可以不修改现有代码的情况下引入新的产品,只要引入新的具体工厂即可。
  • 灵活性和扩展性:工厂模式提高了系统的灵活性和扩展性,通过配置不同的工厂可以得到不同的产品。
*汽车工厂:使用了之前的装饰模式代码
  1. 沙箱化(Sandboxing)是一种计算机安全机制,主要用于隔离程序运行环境,以防止恶意代码或应用程序对系统和数据造成破坏
复制代码
*声音工厂:工厂方法模式
  1. using System.Collections.Generic;  
  2. using UnityEngine;  
  3.   
  4. namespace BytecodePattern  
  5. {  
  6.     public class Wizard  
  7.     {  
  8.         public int Health { get; set; } = 0;  
  9.         public int Wisdom { get; set; } = 0;  
  10.         public int Agility { get; set; } = 0;  
  11.     }  
  12.   
  13.     public class GameController : MonoBehaviour  
  14.     {  
  15.         private Dictionary<int, Wizard> wizards = new();  
  16.   
  17.         private void Start()  
  18.         {  
  19.             wizards.Add(0, new Wizard());  
  20.             wizards.Add(1, new Wizard());  
  21.   
  22.   
  23.             var bytecode = new[] {  
  24.                 (int)Instruction.INST_LITERAL, 0, // 加载索引 0 到栈顶  
  25.                 (int)Instruction.INST_LITERAL, 75, // 加载常量值 75 到栈顶  
  26.                 (int)Instruction.INST_SET_HEALTH, // 设置健康值  
  27.                 (int)Instruction.INST_LITERAL, 1, // 加载索引 1 到栈顶  
  28.                 (int)Instruction.INST_LITERAL, 50, // 加载常量值 50 到栈顶  
  29.                 (int)Instruction.INST_SET_WISDOM, // 设置智慧值  
  30.                 (int)Instruction.INST_LITERAL, 1, // 加载索引 1 到栈顶  
  31.                 (int)Instruction.INST_LITERAL, 60, // 加载常量值 60 到栈顶  
  32.                 (int)Instruction.INST_SET_AGILITY, // 设置敏捷值  
  33.                 (int)Instruction.INST_LITERAL, 0, // 加载索引 0 到栈顶  
  34.                 (int)Instruction.INST_GET_HEALTH, // 获取健康值并推送到栈顶  
  35.                 (int)Instruction.INST_LITERAL, 5, // 加载常量值 5 到栈顶  
  36.                 (int)Instruction.INST_ADD, // 执行加法操作  
  37.             };  
  38.   
  39.             var vm = new VM(this);  
  40.   
  41.             vm.Interpret(bytecode);  
  42.         }  
  43.   
  44.         public void SetHealth(int wizardID, int amount)  
  45.         {  
  46.             wizards[wizardID].Health = amount;  
  47.             Debug.Log($"Wizard {wizardID} sets health {amount}");  
  48.         }  
  49.   
  50.         public void SetWisdom(int wizardID, int amount)  
  51.         {  
  52.             wizards[wizardID].Wisdom = amount;  
  53.             Debug.Log($"Wizard {wizardID} sets wisdom {amount}");  
  54.         }  
  55.   
  56.         public void SetAgility(int wizardID, int amount)  
  57.         {  
  58.             wizards[wizardID].Agility = amount;  
  59.             Debug.Log($"Wizard {wizardID} sets agility {amount}");  
  60.         }  
  61.   
  62.   
  63.         public int GetHealth(int wizardID)  
  64.         {  
  65.             Debug.Log($"Wizard {wizardID} has health {wizards[wizardID].Health}");  
  66.             return wizards[wizardID].Health;  
  67.         }  
  68.   
  69.         public int GetWisdom(int wizardID)  
  70.         {  
  71.             Debug.Log($"Wizard {wizardID} has wisdom {wizards[wizardID].Wisdom}");  
  72.             return wizards[wizardID].Wisdom;  
  73.         }  
  74.   
  75.         public int GetAgility(int wizardID)  
  76.         {  
  77.             Debug.Log($"Wizard {wizardID} has agility {wizards[wizardID].Agility}");  
  78.             return wizards[wizardID].Agility;  
  79.         }  
  80.     }  
  81. }
  82. namespace BytecodePattern  
  83. {  
  84.     // 编程语言中可以选择的指令  
  85.     public enum Instruction  
  86.     {  
  87.         //Write stats  
  88.         INST_SET_HEALTH,  
  89.         INST_SET_WISDOM,  
  90.         INST_SET_AGILITY,  
  91.   
  92.         //字面量  
  93.         INST_LITERAL,  
  94.   
  95.         //Read stats  
  96.         INST_GET_HEALTH,  
  97.         INST_GET_WISDOM,  
  98.         INST_GET_AGILITY,  
  99.   
  100.         //Arithmetic  
  101.         INST_ADD,  
  102.         INST_SUBTRACT,  
  103.         INST_MULTIPLY,  
  104.         INST_DIVIDE,  
  105.         INST_MODULO,  
  106.     }  
  107. }
  108. using System.Collections.Generic;  
  109. using UnityEngine;  
  110.   
  111. namespace BytecodePattern  
  112. {  
  113.     public class VM  
  114.     {  
  115.         private GameController gameController;  
  116.         private Stack<int> stackMachine = new(); //Will store values for later use in the switch statement  
  117.         private const int MAX_STACK = 128; //The max size of the stack  
  118.   
  119.         public VM(GameController gameController)  
  120.         {  
  121.             this.gameController = gameController;  
  122.         }  
  123.   
  124.         public void Interpret(int[] bytecode)  
  125.         {  
  126.             stackMachine.Clear();  
  127.   
  128.             // Read and execute the instructions  
  129.             for (var i = 0; i < bytecode.Length; i++)  
  130.             {  
  131.                 // Convert from int to enum  
  132.                 var instruction = (Instruction)bytecode[i];  
  133.   
  134.                 switch (instruction)  
  135.                 {  
  136.                     case Instruction.INST_SET_HEALTH:  
  137.                     {  
  138.                         int amount = Pop();  
  139.                         int wizard = Pop();  
  140.                         gameController.SetHealth(wizard, amount);  
  141.                         break;  
  142.                     }  
  143.                     case Instruction.INST_SET_WISDOM:  
  144.                     {  
  145.                         int amount = Pop();  
  146.                         int wizard = Pop();  
  147.                         gameController.SetWisdom(wizard, amount);  
  148.                         break;  
  149.                     }  
  150.                     case Instruction.INST_SET_AGILITY:  
  151.                     {  
  152.                         int amount = Pop();  
  153.                         int wizard = Pop();  
  154.                         gameController.SetAgility(wizard, amount);  
  155.                         break;  
  156.                     }  
  157.                     case Instruction.INST_LITERAL:  
  158.                     {  
  159.                         Push(bytecode[++i]);  
  160.                         break;  
  161.                     }  
  162.                     case Instruction.INST_GET_HEALTH:  
  163.                     {  
  164.                         int wizard = Pop();  
  165.                         Push(gameController.GetHealth(wizard));  
  166.                         break;  
  167.                     }  
  168.                     case Instruction.INST_GET_WISDOM:  
  169.                     {  
  170.                         int wizard = Pop();  
  171.                         Push(gameController.GetWisdom(wizard));  
  172.                         break;  
  173.                     }  
  174.                     case Instruction.INST_GET_AGILITY:  
  175.                     {  
  176.                         int wizard = Pop();  
  177.                         Push(gameController.GetAgility(wizard));  
  178.                         break;  
  179.                     }  
  180.                     case Instruction.INST_ADD:  
  181.                     {  
  182.                         int b = Pop();  
  183.                         int a = Pop();  
  184.                         Push(a + b);  
  185.                         break;  
  186.                     }  
  187.                     case Instruction.INST_SUBTRACT:  
  188.                     {  
  189.                         int b = Pop();  
  190.                         int a = Pop();  
  191.                         Push(a - b);  
  192.                         break;  
  193.                     }  
  194.                     case Instruction.INST_MULTIPLY:  
  195.                     {  
  196.                         int b = Pop();  
  197.                         int a = Pop();  
  198.                         Push(a * b);  
  199.                         break;  
  200.                     }  
  201.                     case Instruction.INST_DIVIDE:  
  202.                     {  
  203.                         int b = Pop();  
  204.                         int a = Pop();  
  205.                         if (b != 0)  
  206.                         {  
  207.                             Push(a / b);  
  208.                         }  
  209.                         else  
  210.                         {  
  211.                             Debug.LogError("Division by zero error");  
  212.                         }  
  213.   
  214.                         break;  
  215.                     }  
  216.                     case Instruction.INST_MODULO:  
  217.                     {  
  218.                         int b = Pop();  
  219.                         int a = Pop();  
  220.                         if (b != 0)  
  221.                         {  
  222.                             Push(a % b);  
  223.                         }  
  224.                         else  
  225.                         {  
  226.                             Debug.LogError("Modulo by zero error");  
  227.                         }  
  228.   
  229.                         break;  
  230.                     }  
  231.                     default:  
  232.                     {  
  233.                         Debug.Log($"The VM couldn't find the instruction {instruction} :(");  
  234.                         break;  
  235.                     }  
  236.                 }  
  237.             }  
  238.         }  
  239.   
  240.   
  241.         private int Pop()  
  242.         {  
  243.             if (stackMachine.Count == 0)  
  244.             {  
  245.                 Debug.LogError("The stack is empty :(");  
  246.             }  
  247.   
  248.             return stackMachine.Pop();  
  249.         }  
  250.   
  251.         private void Push(int number)  
  252.         {  
  253.             //检查栈溢出,有人制作一个试图破坏你的游戏的模组时很有用  
  254.             if (stackMachine.Count + 1 > MAX_STACK)  
  255.             {  
  256.                 Debug.LogError("Stack overflow is not just a place where you copy and paste code!");  
  257.             }  
  258.   
  259.             stackMachine.Push(number);  
  260.         }  
  261.     }  
  262. }
复制代码
使用抽象类实现抽象工厂github链接
*UI工厂:抽象工厂模式
  1. using UnityEngine;  
  2. using UnityEngine.UI;  
  3.   
  4. namespace DirtyFlag  
  5. {  
  6.     public class UnsavedChangesController : MonoBehaviour  
  7.     {  
  8.         // 私有布尔变量,用作“脏”标志(dirty flag),用来表示自上次保存以来是否发生了更改。  
  9.         private bool isSaved = true;  
  10.         private readonly float speed = 5f;  
  11.         public Button saveBtn;  
  12.         public GameObject warningMessage;  
  13.   
  14.         private void Start()  
  15.         {  
  16.             saveBtn.onClick.AddListener(Save);  
  17.         }  
  18.   
  19.         private void Update()  
  20.         {  
  21.             if (Input.GetKey(KeyCode.W))  
  22.             {  
  23.                 transform.Translate(speed * Time.deltaTime * Vector3.up);  
  24.                 // 标记为已修改(未保存)  
  25.                 isSaved = false;  
  26.             }  
  27.   
  28.             if (Input.GetKey(KeyCode.S))  
  29.             {  
  30.                 transform.Translate(speed * Time.deltaTime * -Vector3.up);  
  31.                 // 标记为已修改(未保存)  
  32.                 isSaved = false;  
  33.             }  
  34.   
  35.             if (Input.GetKey(KeyCode.A))  
  36.             {  
  37.                 transform.Translate(speed * Time.deltaTime * -Vector3.right);  
  38.                 // 标记为已修改(未保存)  
  39.                 isSaved = false;  
  40.             }  
  41.   
  42.             if (Input.GetKey(KeyCode.D))  
  43.             {  
  44.                 transform.Translate(speed * Time.deltaTime * Vector3.right);  
  45.                 // 标记为已修改(未保存)  
  46.                 isSaved = false;  
  47.             }  
  48.   
  49.             warningMessage.SetActive(!isSaved); // 如果isSaved为false,显示警告信息,提示用户有未保存的更改  
  50.         }  
  51.   
  52.         private void Save()  
  53.         {  
  54.             Debug.Log("Game was saved");  
  55.             isSaved = true;  
  56.         }  
  57.     }  
  58. }
复制代码
外观模式

***外观模式(Facade Pattern)是一种结构型设计模式,其核心思想是为子系统中的一组接口提供一个一致的界面。这种模式通过引入一个外观类来简化客户端与子系统之间的交互,从而隐藏系统的复杂性。
***定义
外观模式定义了一个高层接口,使得子系统更容易使用。它允许客户端通过一个统一的入口点来与系统进行通信,而不需要了解系统内部的具体细节和复杂性。
***适用场景

  • 当需要简化复杂系统的使用和理解时,外观模式是一个强大的工具。它可以将系统的复杂性隐藏在背后,提供一个简洁的接口给客户端。
  • 当一个系统由多个子系统组成,并且客户端需要通过不同的接口与这些子系统进行交互时,外观模式可以将这些交互整合在一个统一的接口中,方便客户端的使用。
***优点

  • 简化了调用过程,无需了解深入子系统,防止带来风险。
  • 减少系统依赖、松散耦合。
  • 更好的划分访问层次。
  • 符合迪米特法则,即最少知道原则。
***缺点

  • 增加子系统、扩展子系统行为容易引入风险。
  • 不符合开闭原则。
***实现方式

  • 创建外观类:定义一个外观类,作为客户端与子系统之间的中介
  • 封装子系统操作:外观类将复杂的子系统操作封装成简单的方法
  1. using System.Collections.Generic;  
  2. using UnityEngine;  
  3.   
  4. namespace ObjectPool.Simple  
  5. {  
  6.         // 简单的对象池实现  
  7.     public class BulletObjectPoolSimple : ObjectPoolBase  
  8.     {  
  9.         // 子弹预制件,用来实例化新的子弹  
  10.         public MoveBullet bulletPrefab;  
  11.   
  12.         // 保存已池化的子弹对象  
  13.         private readonly List<GameObject> bullets = new();  
  14.   
  15.         private void Start()  
  16.         {  
  17.             if (bulletPrefab == null)  
  18.             {  
  19.                 Debug.LogError("需要子弹预制件的引用");  
  20.             }  
  21.   
  22.             // 实例化新子弹并放入列表供以后使用  
  23.             for (var i = 0; i < INITIAL_POOL_SIZE; i++)  
  24.             {  
  25.                 GenerateBullet();  
  26.             }  
  27.         }  
  28.   
  29.         // 生成单个新子弹并将其放入列表  
  30.         private void GenerateBullet()  
  31.         {  
  32.             GameObject newBullet = Instantiate(bulletPrefab.gameObject, transform);  
  33.             newBullet.SetActive(false); // 停用子弹,准备放入池中  
  34.             bullets.Add(newBullet); // 将子弹添加到池中  
  35.         }  
  36.   
  37.         // 从池中获取一个子弹  
  38.         public GameObject GetBullet()  
  39.         {  
  40.             // 尝试找到一个未激活的子弹  
  41.             foreach (GameObject bullet in bullets)  
  42.             {  
  43.                 if (!bullet.activeInHierarchy) // 检查子弹是否处于非活动状态  
  44.                 {  
  45.                     bullet.SetActive(true); // 激活子弹  
  46.                     return bullet; // 返回激活的子弹  
  47.                 }  
  48.             }  
  49.   
  50.             // 如果没有可用的子弹并且池子还没有满,就创建一个新的子弹  
  51.             if (bullets.Count < MAX_POOL_SIZE)  
  52.             {  
  53.                 GenerateBullet();  
  54.   
  55.                 // 新子弹是列表中的最后一个元素  
  56.                 GameObject lastBullet = bullets[^1];  
  57.                 lastBullet.SetActive(true);  
  58.   
  59.                 return lastBullet;  
  60.             }  
  61.   
  62.             // 如果池子满了或者找不到可用的子弹,返回null  
  63.             return null;  
  64.         }  
  65.     }  
  66. }
复制代码
模板方法模式

***模板方法模式(Template Method Pattern)是一种行为型设计模式,它定义了一个操作中的算法骨架,而将一些步骤的实现延迟到子类中。这种模式允许子类在不改变算法结构的情况下重新定义算法的某些特定步骤。
***定义
模板方法模式定义了一个算法的骨架,并允许子类为一个或多个步骤提供实现。这使得子类可以在不改变算法结构的前提下,重新定义算法的某些步骤。
***主要解决的问题
模板方法模式解决在多个子类中重复实现相同的方法的问题,通过将通用方法抽象到父类中来避免代码重复。
***使用场景

  • 当存在一些通用的方法,可以在多个子类中共用时。
  • 算法的整体步骤很固定,但其中个别部分易变时。
***实现方式

  • 定义抽象父类:包含模板方法和一些抽象方法或具体方法。
  • 实现子类:继承抽象父类并实现抽象方法,不改变算法结构。
***关键代码

  • 模板方法:在抽象父类中定义,调用抽象方法和具体方法。
  • 抽象方法:由子类实现,代表算法的可变部分。
  • 具体方法:在抽象父类中实现,代表算法的不变部分。
***优点

  • 封装不变部分:算法的不变部分被封装在父类中。
  • 扩展可变部分:子类可以扩展或修改算法的可变部分。
  • 提取公共代码:减少代码重复,便于维护。
***缺点

  • 增加复杂性:类数量增加,增加了系统复杂性。
  • 继承缺点:模板方法主要通过继承实现,继承关系自身就有缺点
  1. using System.Collections.Generic;  
  2. using UnityEngine;  
  3.   
  4. namespace ObjectPool.Optimized  
  5. {  
  6.     // 这个对象池实现更加复杂但性能更好  
  7.     public class BulletObjectPoolOptimized : ObjectPoolBase  
  8.     {  
  9.         // 子弹预制件,用来实例化新的子弹  
  10.         public MoveBulletOptimized bulletPrefab;  
  11.   
  12.         // 保存已池化的子弹  
  13.         private readonly List<MoveBulletOptimized> bullets = new();  
  14.   
  15.         // 第一个可用的子弹,不用遍历列表查找  
  16.         // 创建一个链表,所有未使用的子弹链接在一起  
  17.         private MoveBulletOptimized firstAvailable;  
  18.   
  19.         private void Start()  
  20.         {  
  21.             if (bulletPrefab == null)  
  22.             {  
  23.                 Debug.LogError("需要子弹预制件的引用");  
  24.             }  
  25.   
  26.             // 实例化新子弹并放入列表供以后使用  
  27.             for (var i = 0; i < INITIAL_POOL_SIZE; i++)  
  28.             {  
  29.                 GenerateBullet();  
  30.             }  
  31.   
  32.             // 构建链表  
  33.             firstAvailable = bullets[0];  
  34.   
  35.             // 每个子弹指向下一个  
  36.             for (var i = 0; i < bullets.Count - 1; i++)  
  37.             {  
  38.                 bullets[i].next = bullets[i + 1];  
  39.             }  
  40.   
  41.             // 最后一个子弹终止链表  
  42.             bullets[^1].next = null;  
  43.         }  
  44.   
  45.         // 生成单个新子弹并放入列表  
  46.         private void GenerateBullet()  
  47.         {  
  48.             MoveBulletOptimized newBullet = Instantiate(bulletPrefab, transform);  
  49.             newBullet.gameObject.SetActive(false);  
  50.             bullets.Add(newBullet);  
  51.             newBullet.objectPool = this; // 设置子弹的对象池引用  
  52.         }  
  53.   
  54.         // 子弹被停用时添加到链表中  
  55.         public void ConfigureDeactivatedBullet(MoveBulletOptimized deactivatedObj)  
  56.         {  
  57.             // 将其作为链表的第一个元素,避免检查第一个是否为null  
  58.             deactivatedObj.next = firstAvailable;  
  59.             firstAvailable = deactivatedObj;  
  60.         }  
  61.   
  62.         // 获取一个子弹  
  63.         public GameObject GetBullet()  
  64.         {  
  65.             // 不是遍历列表查找不活动对象,而是直接获取firstAvailable对象  
  66.             if (firstAvailable == null)  
  67.             {  
  68.                 // 如果没有更多子弹可用了,我们根据最大池大小决定是否实例化新的子弹  
  69.                 if (bullets.Count < MAX_POOL_SIZE)  
  70.                 {  
  71.                     GenerateBullet();  
  72.                     MoveBulletOptimized lastBullet = bullets[^1];  
  73.                     ConfigureDeactivatedBullet(lastBullet);  
  74.                 }  
  75.                 else  
  76.                 {  
  77.                     return null;  
  78.                 }  
  79.             }  
  80.   
  81.             // 从链表中移除  
  82.             MoveBulletOptimized newBullet = firstAvailable;  
  83.             firstAvailable = newBullet.next;  
  84.   
  85.             GameObject newBulletGO = newBullet.gameObject;  
  86.             newBulletGO.SetActive(true);  
  87.   
  88.             return newBulletGO;  
  89.         }  
  90.     }  
  91. }
  92. namespace ObjectPool.Optimized  
  93. {  
  94.         // 继承自 BulletBase 类,用于优化子弹移动逻辑  
  95.     public class MoveBulletOptimized : BulletBase  
  96.     {  
  97.         // 用于优化对象池性能,创建一个链表结构  
  98.         [System.NonSerialized] public MoveBulletOptimized next;  
  99.   
  100.         // 对象池引用,以便在子弹停用时通知对象池  
  101.         [System.NonSerialized] public BulletObjectPoolOptimized objectPool;  
  102.   
  103.         private void Update()  
  104.         {  
  105.             MoveBullet(); // 调用基类方法移动子弹  
  106.   
  107.             // 如果子弹超出有效距离,则停用它  
  108.             if (IsBulletDead())  
  109.             {  
  110.                 // 告诉对象池此子弹已被停用  
  111.                 objectPool.ConfigureDeactivatedBullet(this);  
  112.   
  113.                 gameObject.SetActive(false); // 停用子弹的游戏对象  
  114.             }  
  115.         }  
  116.     }  
  117. }
复制代码
备忘录模式

***备忘录模式(Memento Pattern)是一种行为型设计模式,它允许在不破坏对象封装性的前提下,捕获并保存对象的内部状态,以便在将来恢复到之前的状态。这种模式特别适用于实现撤销(Undo)操作的功能。
***定义

  • 发起人(Originator):创建并恢复备忘录的对象,负责定义哪些属于备份范围的状态。
  • 备忘录(Memento):存储发起人内部状态的快照,并且防止其他对象访问备忘录。备忘录通常只有发起人可以访问其内容。
  • 管理者(Caretaker):负责保存和恢复备忘录,但不能检查或操作备忘录的内容。
***应用场景

  • 文本编辑器:实现撤销和重做功能。
  • 游戏开发:保存游戏进度,允许玩家在失败时重新开始。
  • 数据库事务:保存事务开始前的状态,以便在事务失败时回滚。
  • 图形界面:保存画布或绘图状态,以便用户可以撤销之前的绘图操作。
***实现方式

  • 发起人(Originator)类,它负责维护内部状态,并可以创建备忘录对象和从备忘录对象中恢复状态。
  • 备忘录(Memento)类,用于存储发起人的内部状态。备忘录类应该提供方法来获取和设置状态。
  • 管理者(Caretaker)类,它负责管理备忘录对象。通常,管理者会维护一个备忘录列表,可以添加和检索备忘录对象。
  • 在发起人类中添加方法来创建备忘录对象和从备忘录对象中恢复状态。
***优点

  • 提供了一种可以恢复状态的机制,方便地将数据恢复到某个历史状态。
  • 实现了内部状态的封装,除了创建它的发起人之外,其他对象都不能访问这些状态信息。
  • 简化了发起人类,发起人不需要管理和保存其内部状态的各个备份,所有状态信息都保存在备忘录中,并由管理者进行管理。
  1. using UnityEngine;  
  2. using UnityEngine.Pool;  
  3.   
  4. namespace ObjectPool.UnityNative  
  5. {  
  6.         // 使用Unity的原生对象池系统  
  7.     public class BulletObjectPoolUnity : ObjectPoolBase  
  8.     {  
  9.         // 子弹预制件,用来实例化新的子弹  
  10.         public MoveBulletUnity bulletPrefab;  
  11.   
  12.         // Unity的原生对象池  
  13.         private ObjectPool<MoveBulletUnity> allBullets;  
  14.   
  15.         private void Start()  
  16.         {  
  17.             if (bulletPrefab == null)  
  18.             {  
  19.                 Debug.LogError("需要子弹预制件的引用");  
  20.             }  
  21.   
  22.             // 创建一个新的对象池  
  23.             allBullets = new ObjectPool<MoveBulletUnity>(  
  24.                 CreatePooledItem, // 创建池中对象的回调函数  
  25.                 OnTakeFromPool, // 从池中取出对象时的回调函数  
  26.                 OnReturnedToPool, // 将对象返回到池中时的回调函数  
  27.                 OnDestroyPoolObject, // 当池达到容量并有对象被返回时销毁对象的回调函数  
  28.                 true, // 是否启用集合检查(防止重复释放)  
  29.                 INITIAL_POOL_SIZE, // 初始池大小  
  30.                 MAX_POOL_SIZE); // 最大池大小  
  31.         }  
  32.   
  33.         private void Update()  
  34.         {  
  35.             // 调试信息:显示当前池状态  
  36.             Debug.Log($"In pool: {allBullets.CountAll}, Active: {allBullets.CountActive}, Inactive: {allBullets.CountInactive}");  
  37.   
  38.             // 按下K键清空对象池  
  39.             if (Input.GetKeyDown(KeyCode.K))  
  40.             {  
  41.                 allBullets.Clear(); // 清空对象池而不是Dispose(),因为Dispose()会完全摧毁池子。  
  42.             }  
  43.         }  
  44.   
  45.         // 创建新项并添加到池中  
  46.         private MoveBulletUnity CreatePooledItem()  
  47.         {  
  48.             GameObject newBullet = Instantiate(bulletPrefab.gameObject, transform);  
  49.             var moveBulletScript = newBullet.GetComponent<MoveBulletUnity>();  
  50.             moveBulletScript.objectPool = allBullets; // 设置子弹的对象池引用以便在子弹死亡时返回池中  
  51.             return moveBulletScript;  
  52.         }  
  53.   
  54.         // 当从池中获取对象时调用  
  55.         private void OnTakeFromPool(MoveBulletUnity bullet)  
  56.         {  
  57.             bullet.gameObject.SetActive(true); // 激活子弹  
  58.         }  
  59.   
  60.         // 当对象被返回到池中时调用  
  61.         private void OnReturnedToPool(MoveBulletUnity bullet)  
  62.         {  
  63.             bullet.gameObject.SetActive(false); // 停用子弹  
  64.         }  
  65.   
  66.         // 如果池容量已满,则任何返回的对象将被销毁  
  67.         private void OnDestroyPoolObject(MoveBulletUnity bullet)  
  68.         {  
  69.             Debug.Log("销毁池化对象");  
  70.             Destroy(bullet.gameObject); // 销毁子弹  
  71.         }  
  72.   
  73.         // 从池中获取一个子弹  
  74.         public GameObject GetBullet()  
  75.         {  
  76.             // 从池中获取一个实例。如果池为空,则创建一个新实例  
  77.             return allBullets.Get().gameObject;  
  78.         }  
  79.     }  
  80. }
  81. using UnityEngine.Pool;  
  82.   
  83. namespace ObjectPool.UnityNative  
  84. {  
  85.     public class MoveBulletUnity : BulletBase  
  86.     {  
  87.         // 对象池引用,用于停用子弹时将其返回池中  
  88.         public IObjectPool<MoveBulletUnity> objectPool;  
  89.   
  90.         private void Update()  
  91.         {  
  92.             MoveBullet(); // 移动子弹  
  93.   
  94.             // 如果子弹超出有效距离,则停用它  
  95.             if (IsBulletDead())  
  96.             {  
  97.                 // 返回实例到池中  
  98.                 objectPool.Release(this);  
  99.             }  
  100.         }  
  101.     }  
  102. }
复制代码
  1. using System.Collections.Generic;  
  2. using UnityEngine;  
  3.   
  4. namespace SpatialPartition.Scripts  
  5. {  
  6.     // 单位可以互相战斗,它们会改变颜色,并且颜色会保持一段时间以便观察效果
  7.     public class GameController : MonoBehaviour  
  8.     {  
  9.         public Unit unitPrefab;  
  10.         public Transform unitParentTrans;  
  11.   
  12.         private Grid grid;  
  13.         private const int NUMBER_OF_UNITS = 100; // 地图上移动的单位数量  
  14.         private HashSet<Unit> allUnits = new(); // 用于跟踪所有单位以便移动它们  
  15.         private Material gridMaterial;  
  16.         private Mesh gridMesh;  
  17.   
  18.         private void Start()  
  19.         {  
  20.             grid = new Grid();  
  21.   
  22.             float battlefieldWidth = Grid.NUM_CELLS * Grid.CELL_SIZE;  
  23.   
  24.             for (var i = 0; i < NUMBER_OF_UNITS; i++)  
  25.             {  
  26.                 float randomX = Random.Range(0f, battlefieldWidth);  
  27.                 float randomZ = Random.Range(0f, battlefieldWidth);  
  28.                 var randomPos = new Vector3(randomX, 0f, randomZ);  
  29.   
  30.                 Unit newUnit = Instantiate(unitPrefab, unitParentTrans);  
  31.                 // 初始化单位,这会将其添加到网格中  
  32.                 newUnit.InitUnit(grid, randomPos);  
  33.                 // 将单位添加到所有单位的集合中  
  34.                 allUnits.Add(newUnit);  
  35.             }  
  36.         }  
  37.   
  38.         private void Update()  
  39.         {  
  40.             foreach (Unit unit in allUnits)  
  41.             {  
  42.                 unit.Move(Time.deltaTime);  
  43.             }  
  44.   
  45.             grid.HandleMelee();  
  46.         }  
  47.   
  48.         private void LateUpdate()  
  49.         {  
  50.             // 显示网格  
  51.             if (gridMaterial == null)  
  52.             {  
  53.                 // 创建网格材质并设置颜色为黑色  
  54.                 gridMaterial = new Material(Shader.Find("Unlit/Color"));  
  55.                 gridMaterial.color = Color.black;  
  56.             }  
  57.   
  58.             if (grid == null)  
  59.             {  
  60.                 return;  
  61.             }  
  62.   
  63.             if (gridMesh == null)  
  64.             {  
  65.                 // 初始化网格网格对象  
  66.                 gridMesh = InitGridMesh();  
  67.             }  
  68.   
  69.             // 绘制网格  
  70.             Graphics.DrawMesh(gridMesh, Vector3.zero, Quaternion.identity, gridMaterial, 0, Camera.main, 0);  
  71.         }  
  72.   
  73.         private Mesh InitGridMesh()  
  74.         {  
  75.             // 生成顶点  
  76.             var lineVertices = new List<Vector3>();  
  77.             float battlefieldWidth = Grid.NUM_CELLS * Grid.CELL_SIZE;  
  78.             Vector3 linePosX = Vector3.zero;  
  79.             Vector3 linePosY = Vector3.zero;  
  80.             for (var x = 0; x <= Grid.NUM_CELLS; x++)  
  81.             {  
  82.                 lineVertices.Add(linePosX);  
  83.                 lineVertices.Add(linePosX + (Vector3.right * battlefieldWidth));  
  84.                 lineVertices.Add(linePosY);  
  85.                 lineVertices.Add(linePosY + (Vector3.forward * battlefieldWidth));  
  86.                 linePosX += Vector3.forward * Grid.CELL_SIZE;  
  87.                 linePosY += Vector3.right * Grid.CELL_SIZE;  
  88.             }  
  89.   
  90.             // 生成索引  
  91.             var indices = new List<int>();  
  92.             for (var i = 0; i < lineVertices.Count; i++)  
  93.             {  
  94.                 indices.Add(i);  
  95.             }  
  96.   
  97.             // 生成网格  
  98.             var gridMesh = new Mesh();  
  99.             gridMesh.SetVertices(lineVertices);  
  100.             gridMesh.SetIndices(indices, MeshTopology.Lines, 0);  
  101.             return gridMesh;  
  102.         }  
  103.     }  
  104. }
  105. using UnityEngine;  
  106.   
  107. namespace SpatialPartition.Scripts  
  108. {  
  109.     // 网格类,同时处理战斗  
  110.     public class Grid  
  111.     {  
  112.         public const int NUM_CELLS = 6;  
  113.         public const int CELL_SIZE = 6;  
  114.   
  115.         private Unit[] cells;  
  116.   
  117.         // 网格上有多少单位,这比遍历所有单元格并计数更快  
  118.         public int unitCount { get; private set; }  
  119.   
  120.         public Grid()  
  121.         {  
  122.             cells = new Unit[NUM_CELLS * NUM_CELLS];  
  123.             for (var x = 0; x < NUM_CELLS; x++)  
  124.             {  
  125.                 for (var y = 0; y < NUM_CELLS; y++)  
  126.                 {  
  127.                     cells[GetIndex(x, y)] = null;  
  128.                 }  
  129.             }  
  130.         }  
  131.   
  132.         private int GetIndex(int x, int y)  
  133.         {  
  134.             return (y * NUM_CELLS) + x;  
  135.         }  
  136.   
  137.         // 添加单位到网格  
  138.         // 当单位已经在网格中并移动到新单元格时也会使用此方法  
  139.         public void Add(Unit newUnit, bool isNewUnit = false)  
  140.         {  
  141.             // 确定单位所在的网格单元格  
  142.             Vector2Int cellPos = ConvertFromWorldToCell(newUnit.transform.position);  
  143.             // 将单位添加到该单元格列表的前面  
  144.             newUnit.prev = null;  
  145.             newUnit.next = cells[GetIndex(cellPos.x, cellPos.y)];  
  146.             // 将单元格与该单位关联  
  147.             cells[GetIndex(cellPos.x, cellPos.y)] = newUnit;  
  148.             // 如果该单元格中已经有单位,它应该指向新单位  
  149.             if (newUnit.next != null)  
  150.             {  
  151.                 newUnit.next.prev = newUnit;  
  152.             }  
  153.   
  154.             if (isNewUnit)  
  155.             {  
  156.                 unitCount += 1;  
  157.             }  
  158.         }  
  159.   
  160.         // 移动网格上的单位 = 查看它是否改变了单元格  
  161.         // 确保 newPos 是网格内的有效位置  
  162.         public void Move(Unit unit, Vector3 oldPos, Vector3 newPos)  
  163.         {  
  164.             // 查看它之前所在的单元格  
  165.             Vector2Int oldCellPos = ConvertFromWorldToCell(oldPos);  
  166.             // 查看它移动到的单元格  
  167.             Vector2Int newCellPos = ConvertFromWorldToCell(newPos);  
  168.             // 如果它没有改变单元格,我们已完成  
  169.             if (oldCellPos.x == newCellPos.x && oldCellPos.y == newCellPos.y)  
  170.             {  
  171.                 return;  
  172.             }  
  173.   
  174.             // 从旧单元格的链表中取消链接  
  175.             UnlinkUnit(unit);  
  176.             // 如果该单位是该单元格链表的头,移除它  
  177.             if (cells[GetIndex(oldCellPos.x, oldCellPos.y)] == unit)  
  178.             {  
  179.                 cells[GetIndex(oldCellPos.x, oldCellPos.y)] = unit.next;  
  180.             }  
  181.   
  182.             // 将其添加回网格中的新单元格  
  183.             Add(unit);  
  184.         }  
  185.   
  186.         // 从链表中取消链接单位  
  187.         private void UnlinkUnit(Unit unit)  
  188.         {  
  189.             if (unit.prev != null)  
  190.             {  
  191.                 // 前一个单位应该获得一个新的下一个单位  
  192.                 unit.prev.next = unit.next;  
  193.             }  
  194.   
  195.             if (unit.next != null)  
  196.             {  
  197.                 // 下一个单位应该获得一个新的前一个单位  
  198.                 unit.next.prev = unit.prev;  
  199.             }  
  200.         }  
  201.   
  202.         // 帮助方法,将 Vector3 转换为单元格位置  
  203.         public Vector2Int ConvertFromWorldToCell(Vector3 pos)  
  204.         {  
  205.             // 将坐标除以单元格大小,从世界空间转换为单元格空间  
  206.             // 转换为 int 类型,从单元格空间转换为单元格索引  
  207.             int cellX = Mathf.FloorToInt(pos.x / CELL_SIZE);  
  208.             int cellY = Mathf.FloorToInt(pos.z / CELL_SIZE); // z 而不是 y,因为 y 是 Unity 坐标系中的向上轴  
  209.             var cellPos = new Vector2Int(cellX, cellY);  
  210.             return cellPos;  
  211.         }  
  212.   
  213.         // 测试位置是否为有效位置(= 是否在网格内)  
  214.         public bool IsPosValid(Vector3 pos)  
  215.         {  
  216.             Vector2Int cellPos = ConvertFromWorldToCell(pos);  
  217.             return cellPos.x is >= 0 and < NUM_CELLS && cellPos.y is >= 0 and < NUM_CELLS;  
  218.         }  
  219.   
  220.         // 战斗处理  
  221.         public void HandleMelee()  
  222.         {  
  223.             for (var x = 0; x < NUM_CELLS; x++)  
  224.             {  
  225.                 for (var y = 0; y < NUM_CELLS; y++)  
  226.                 {  
  227.                     HandleCell(x, y);  
  228.                 }  
  229.             }  
  230.         }  
  231.   
  232.         // 处理单个单元格的战斗  
  233.         private void HandleCell(int x, int y)  
  234.         {  
  235.             Unit unit = cells[GetIndex(x, y)];  
  236.             // 让该单元格中的每个单位与其他单位战斗一次  
  237.             while (unit != null)  
  238.             {  
  239.                 // 尝试与该单元格中的其他单位战斗  
  240.                 HandleUnit(unit, unit.next);  
  241.                 // 我们还应该尝试与周围8个单元格中的单位战斗,因为它们可能也在攻击范围内  
  242.                 // 但我们不能检查所有8个单元格,因为这样有些单位可能会战斗两次,所以我们只检查一半(哪一半不重要)  
  243.                 // 我们还必须检查是否有周围的单元格,因为当前单元格可能是边界  
  244.                 // 这假设攻击距离小于单元格大小,否则我们可能需要检查更多单元格  
  245.                 if (x > 0 && y > 0)  
  246.                 {  
  247.                     HandleUnit(unit, cells[GetIndex(x - 1, y - 1)]);  
  248.                 }  
  249.   
  250.                 if (x > 0)  
  251.                 {  
  252.                     HandleUnit(unit, cells[GetIndex(x - 1, y - 0)]);  
  253.                 }  
  254.   
  255.                 if (y > 0)  
  256.                 {  
  257.                     HandleUnit(unit, cells[GetIndex(x - 0, y - 1)]);  
  258.                 }  
  259.   
  260.                 if (x > 0 && y < NUM_CELLS - 1)  
  261.                 {  
  262.                     HandleUnit(unit, cells[GetIndex(x - 1, y + 1)]);  
  263.                 }  
  264.   
  265.                 unit = unit.next;  
  266.             }  
  267.         }  
  268.   
  269.         // 处理单个单位与链表中的单位的战斗  
  270.         private void HandleUnit(Unit unit, Unit other)  
  271.         {  
  272.             while (other != null)  
  273.             {  
  274.                 // 如果它们的位置相似,则让它们战斗 - 使用平方距离因为它更快  
  275.                 if ((unit.transform.position - other.transform.position).sqrMagnitude < Unit.ATTACK_DISTANCE * Unit.ATTACK_DISTANCE)  
  276.                 {  
  277.                     HandleAttack(unit, other);  
  278.                 }  
  279.   
  280.                 //更新 other 变量,使其指向链表中的下一个单位。这样在下一次循环迭代时,将检查当前单位与下一个单位之间的距离  
  281.                 other = other.next;  
  282.             }  
  283.         }  
  284.   
  285.         // 处理两个单位之间的攻击  
  286.         private void HandleAttack(Unit one, Unit two)  
  287.         {  
  288.             // 插入战斗机制  
  289.             one.StartFighting();  
  290.             two.StartFighting();  
  291.         }  
  292.     }  
  293. }
  294. using System.Collections;  
  295. using UnityEngine;  
  296.   
  297. namespace SpatialPartition.Scripts  
  298. {  
  299.     public class Unit : MonoBehaviour  
  300.     {  
  301.         public GameObject unitBody;  
  302.         private Grid grid;  
  303.         [System.NonSerialized] public Unit prev;  
  304.         [System.NonSerialized] public Unit next;  
  305.         private MeshRenderer meshRenderer;  
  306.         private Color unitColor = Color.white;  
  307.         private float unitSpeed;  
  308.   
  309.         public const float ATTACK_DISTANCE = 1.0f;  
  310.   
  311.         private void Awake()  
  312.         {  
  313.             meshRenderer = unitBody.GetComponent<MeshRenderer>();  
  314.             if (meshRenderer == null)  
  315.             {  
  316.                 Debug.LogError("MeshRenderer not found on unit body.");  
  317.             }  
  318.   
  319.             unitSpeed = Random.Range(1f, 5f);  
  320.             meshRenderer.material.color = unitColor;  
  321.         }  
  322.   
  323.         public void InitUnit(Grid grid, Vector3 startPos)  
  324.         {  
  325.             this.grid = grid ?? throw new System.ArgumentNullException(nameof(grid), "Grid cannot be null when initializing a unit.");  
  326.   
  327.             transform.position = startPos;  
  328.             prev = null;  
  329.             next = null;  
  330.   
  331.             grid.Add(this, true);  
  332.             transform.rotation = GetRandomDirection();  
  333.         }  
  334.   
  335.         public void Move(float dt)  
  336.         {  
  337.             Vector3 oldPos = transform.position;  
  338.             Vector3 newPos = oldPos + (transform.forward * (unitSpeed * dt));  
  339.   
  340.             bool isValid = grid != null && grid.IsPosValid(newPos); // 新位置是否是网格内的有效位置  
  341.             if (isValid)  
  342.             {  
  343.                 transform.position = newPos;  
  344.                 grid.Move(this, oldPos, newPos); // 更新网格,因为单位可能已经改变了单元格  
  345.             }  
  346.             else  
  347.             {  
  348.                 // 尝试找到一个新的有效方向  
  349.                 for (var i = 0; i < 10; i++) // 尝试最多10次  
  350.                 {  
  351.                     transform.rotation = GetRandomDirection();  
  352.                     newPos = oldPos + (transform.forward * (unitSpeed * dt));  
  353.                     if (grid.IsPosValid(newPos))  
  354.                     {  
  355.                         transform.position = newPos;  
  356.                         grid.Move(this, oldPos, newPos);  
  357.                         break;  
  358.                     }  
  359.                 }  
  360.             }  
  361.         }  
  362.   
  363.         private Quaternion GetRandomDirection()  
  364.         {  
  365.             return Quaternion.Euler(new Vector3(0f, Random.Range(0f, 360f), 0f));  
  366.         }  
  367.   
  368.         public void StartFighting()  
  369.         {  
  370.             StopAllCoroutines(); // 停止所有 FightCooldown 协程  
  371.             StartCoroutine(FightCooldown());  
  372.         }  
  373.   
  374.         private IEnumerator FightCooldown()  
  375.         {  
  376.             meshRenderer.sharedMaterial.color = Color.red;  
  377.             yield return new WaitForSeconds(0.2f);  
  378.             meshRenderer.sharedMaterial.color = unitColor;  
  379.         }  
  380.     }  
  381. }
复制代码
策略模式

***策略模式(Strategy Pattern)是一种行为型设计模式,它使你能在运行时改变对象的行为。策略模式通过定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。这种模式让算法的变化独立于使用算法的客户。
***定义

  • 策略模式的核心在于定义算法族,分别封装起来,让它们之间可以互相替换。策略模式让算法的变化,不会影响到使用算法的客户。换言之,策略模式使动态选择算法成为可能。
***主要角色

  • 策略(Strategy):定义所有支持的算法的公共接口。
  • 具体策略(Concrete Strategy):实现策略接口的具体算法。
  • 上下文(Context):使用策略的类,可以动态地改变其行为。
***应用场景

  • 需要在运行时选择算法或行为的场景。
  • 需要封装算法,使得算法可以互换的场景。
  • 需要避免使用多重条件(if-else 或 switch-case)语句来选择算法的场景。
***实现步骤

  • 定义策略接口,声明执行操作的方法。
  • 创建具体策略类,实现策略接口,提供不同的算法实现。
  • 定义上下文类,持有一个策略对象的引用。
  • 根据需要,客户端代码可以在运行时更改上下文所持有的策略引用。
***优点

  • 算法可以独立于使用它的客户而变化。
  • 策略模式使算法的变化独立于使用算法的客户。
  • 可以方便地增加新的算法。
  • 使算法可替换、可组合。
  1. using DecoratorPattern.Extras;  
  2. using UnityEngine;  
  3.   
  4. namespace DecoratorPattern  
  5. {  
  6. // 装饰者模式控制器,管理订单逻辑。  
  7.     public class OrderSystemController : MonoBehaviour  
  8.     {  
  9.         private void Start()  
  10.         {  
  11.             // Order 1: 为 Roadster 添加 Draco 推进器  
  12.             _Car roadster = new Roadster(); // 创建基础 Roadster 实例  
  13.             roadster = new DracoThruster(roadster, 5); // 为 Roadster 添加 Draco 推进器  
  14.   
  15.             Debug.Log($"You ordered: {roadster.GetDescription()} and have to pay ${roadster.Cost()}");  
  16.   
  17.             // Order 2: 为 Cybertruck 添加 Draco 推进器和弹射座椅  
  18.             _Car cybertruck = new Cybertruck(); // 创建基础 Cybertruck 实例  
  19.             cybertruck = new DracoThruster(cybertruck, 2); // 为 Cybertruck 添加 Draco 推进器  
  20.             cybertruck = new EjectionSeat(cybertruck, 1); // 再为 Cybertruck 添加弹射座椅  
  21.   
  22.             Debug.Log($"You ordered: {cybertruck.GetDescription()} and have to pay ${cybertruck.Cost()}");  
  23.   
  24.             // Order 3: 订购 Model S 没有添加任何额外配件  
  25.             _Car modelS = new ModelS(); // 创建基础 Model S 实例  
  26.   
  27.             Debug.Log($"You ordered: {modelS.GetDescription()} and have to pay ${modelS.Cost()}");  
  28.   
  29.             // 模拟一段时间后,某些价格发生了变化。  
  30.             PriceList.dracoThruster -= 20;  
  31.             PriceList.cybertruck -= 100f;  
  32.             PriceList.modelS += 30f;  
  33.   
  34.             Debug.Log("Price changes!");  
  35.   
  36.             // 打印出更新后的订单价格  
  37.             Debug.Log($"You ordered: {roadster.GetDescription()} and have to pay ${roadster.Cost()}");  
  38.             Debug.Log($"You ordered: {cybertruck.GetDescription()} and have to pay ${cybertruck.Cost()}");  
  39.             Debug.Log($"You ordered: {modelS.GetDescription()} and have to pay ${modelS.Cost()}");  
  40.         }  
  41.     }  
  42. }
  43. namespace DecoratorPattern  
  44. {  
  45.         // 价格列表类用于存储车辆基础价格和额外配件的价格。  
  46.     public static class PriceList  
  47.     {  
  48.         // 基础车型价格  
  49.         public static float cybertruck = 150f; // Cybertruck 的基础价格  
  50.         public static float modelS = 200f; // Model S 的基础价格  
  51.         public static float roadster = 350f; // Roadster 的基础价格  
  52.   
  53.         // 额外配件价格  
  54.         public static float dracoThruster = 20f; // Draco 推进器的价格  
  55.         public static float ejectionSeat = 200f; // 弹射座椅的价格  
  56.     }  
  57. }
  58. namespace DecoratorPattern  
  59. {  
  60.     // 抽象类 _Car 是所有具体汽车类的基础,定义了获取描述和计算成本的方法。  
  61.     public abstract class _Car  
  62.     {  
  63.         protected string description; // 存储汽车的描述信息  
  64.   
  65.         // 获取汽车的描述信息,由子类实现。  
  66.         public abstract string GetDescription();  
  67.   
  68.         // 计算汽车的成本,由子类实现。  
  69.         public abstract float Cost();  
  70.     }  
  71. }
  72. namespace DecoratorPattern  
  73. {  
  74.     public class Roadster : _Car  
  75.     {  
  76.         public Roadster()  
  77.         {  
  78.             description = "Roadster";  
  79.         }  
  80.   
  81.         public override string GetDescription()  
  82.         {  
  83.             return description;  
  84.         }  
  85.   
  86.         public override float Cost()  
  87.         {  
  88.             return PriceList.roadster;  
  89.         }  
  90.     }  
  91. }
  92. namespace DecoratorPattern  
  93. {  
  94.     public class Cybertruck : _Car  
  95.     {  
  96.         public Cybertruck()  
  97.         {  
  98.             description = "Cybertruck";  
  99.         }  
  100.   
  101.         public override string GetDescription()  
  102.         {  
  103.             return description;  
  104.         }  
  105.   
  106.         public override float Cost()  
  107.         {  
  108.             return PriceList.cybertruck;  
  109.         }  
  110.     }  
  111. }
  112. namespace DecoratorPattern  
  113. {  
  114.     public class ModelS : _Car  
  115.     {  
  116.         public ModelS()  
  117.         {  
  118.             description = "Model S";  
  119.         }  
  120.   
  121.         public override string GetDescription()  
  122.         {  
  123.             return description;  
  124.         }  
  125.   
  126.         public override float Cost()  
  127.         {  
  128.             return PriceList.modelS;  
  129.         }  
  130.     }  
  131. }
  132. namespace DecoratorPattern.Extras  
  133. {  
  134.     // 抽象类 _CarExtras 用作所有汽车配件的基础类,它继承自 _Car 类  
  135.     // 这个类允许我们创建具体的装饰器来为汽车对象动态地添加行为  
  136.     public abstract class _CarExtras : _Car  
  137.     {  
  138.         protected int howMany; // 配件的数量  
  139.         protected _Car prevCarPart; // 被装饰的汽车对象引用  
  140.   
  141.         // 构造函数接收一个要装饰的 _Car 对象以及配件的数量  
  142.         public _CarExtras(_Car prevCarPart, int howMany)  
  143.         {  
  144.             this.prevCarPart = prevCarPart;  
  145.             this.howMany = howMany;  
  146.         }  
  147.     }  
  148. }
  149. namespace DecoratorPattern.Extras  
  150. {  
  151.     // 具体的装饰器类 DracoThruster 继承自 _CarExtras 类,用来为汽车添加 Draco 推进器  
  152.     public class DracoThruster : _CarExtras  
  153.     {  
  154.         public DracoThruster(_Car prevCarPart, int howMany) : base(prevCarPart, howMany) { }  
  155.   
  156.         public override string GetDescription()  
  157.         {  
  158.             return $"{prevCarPart.GetDescription()}, {howMany} Draco Thruster";  
  159.         }  
  160.   
  161.         public override float Cost()  
  162.         {  
  163.             return (PriceList.dracoThruster * howMany) + prevCarPart.Cost();  
  164.         }  
  165.     }  
  166. }
  167. namespace DecoratorPattern.Extras  
  168. {  
  169.     // 具体的装饰器类 EjectionSeat 继承自 _CarExtras 类,用来为汽车添加弹射座椅。  
  170.     public class EjectionSeat : _CarExtras  
  171.     {  
  172.         public EjectionSeat(_Car prevCarPart, int howMany) : base(prevCarPart, howMany) { }  
  173.   
  174.         public override string GetDescription()  
  175.         {  
  176.             return $"{prevCarPart.GetDescription()}, {howMany} Ejection Seat";  
  177.         }  
  178.   
  179.         public override float Cost()  
  180.         {  
  181.             return (PriceList.ejectionSeat * howMany) + prevCarPart.Cost();  
  182.         }  
  183.     }  
  184. }
复制代码
  1. using System.Collections.Generic;  
  2. using DecoratorPattern;  
  3. using UnityEngine;  
  4.   
  5. namespace FactoryPattern.CarFactory  
  6. {  
  7.         // 展示工厂模式和装饰者模式的结合使用,用于创建不同配置的汽车对象。  
  8.     public class CarFactoryController : MonoBehaviour  
  9.     {  
  10.         // Start 方法是 Unity 的生命周期方法之一,在场景加载并初始化后立即调用。  
  11.         private void Start()  
  12.         {  
  13.             // 创建两个不同的工厂实例,分别代表美国工厂和中国工厂。  
  14.             _CarFactory US_Factory = new USFactory(); // 美国工厂实例  
  15.             _CarFactory China_Factory = new ChinaFactory(); // 中国工厂实例  
  16.   
  17.             // 使用美国工厂制造 Model S 型号的汽车,并添加 EjectionSeat 配件。  
  18.             _Car order1 = US_Factory.ManufactureCar(new CarInfo(CarModels.ModelS, new List<CarExtras> { CarExtras.EjectionSeat, }, 1));  
  19.             FinalizeOrder(order1); // 处理完成的订单  
  20.   
  21.             // 使用中国工厂制造 Cybertruck 型号的汽车,并添加 DracoThruster 配件。  
  22.             _Car order2 = China_Factory.ManufactureCar(  
  23.                 new CarInfo(CarModels.Cybertruck, new List<CarExtras> { CarExtras.DracoThruster, }, 1));  
  24.             FinalizeOrder(order2); // 处理完成的订单  
  25.   
  26.             // 再次使用美国工厂制造 Roadster 型号的汽车,并添加多个DracoThruster配件  
  27.             _Car order3 = US_Factory.ManufactureCar(new CarInfo(CarModels.Roadster, new List<CarExtras> { CarExtras.DracoThruster, }, 2));  
  28.             FinalizeOrder(order3); // 处理完成的订单  
  29.         }  
  30.   
  31.         // FinalizeOrder 方法用于处理已完成的订单,打印出汽车描述和价格信息  
  32.         private void FinalizeOrder(_Car finishedCar)  
  33.         {  
  34.             Debug.Log(finishedCar == null // 如果成品车为空,则表示无法制造订单  
  35.                 ? $"Sorry but we can't manufacture your order, please try again!" // 输出错误信息  
  36.                 : $"Your order: {finishedCar.GetDescription()} is ready for delivery as soon as you pay ${finishedCar.Cost()}"); // 输出汽车描述和需要支付的金额  
  37.         }  
  38.     }  
  39.   
  40.     public struct CarInfo  
  41.     {  
  42.         public CarModels Model;  
  43.         public List<CarExtras> Extras;  
  44.         public int ExtrasNumber;  
  45.   
  46.         public CarInfo(CarModels model, List<CarExtras> extras, int number)  
  47.         {  
  48.             Model = model;  
  49.             Extras = extras;  
  50.             ExtrasNumber = number;  
  51.         }  
  52.     }  
  53.   
  54.     // CarModels 枚举定义了可用的汽车型号  
  55.     public enum CarModels  
  56.     {  
  57.         ModelS,  
  58.         Roadster,  
  59.         Cybertruck,  
  60.     }  
  61.   
  62.     // CarExtras 枚举定义了可选的汽车配件  
  63.     public enum CarExtras  
  64.     {  
  65.         EjectionSeat, // 弹射座椅  
  66.         DracoThruster, // 推进器  
  67.     }  
  68. }
  69. using DecoratorPattern;  
  70.   
  71. namespace FactoryPattern.CarFactory  
  72. {  
  73.     // 抽象工厂类,定义了一个制造汽车的方法  
  74.     public abstract class _CarFactory  
  75.     {  
  76.         // 这个方法是所谓的“工厂方法”,它用于创建特定类型的汽车  
  77.         public abstract _Car ManufactureCar(CarInfo carInfo);  
  78.     }  
  79. }
  80. using System.Collections.Generic;  
  81. using DecoratorPattern;  
  82. using DecoratorPattern.Extras;  
  83. using UnityEngine;  
  84.   
  85. namespace FactoryPattern.CarFactory  
  86. {  
  87.     public class ChinaFactory : _CarFactory  
  88.     {  
  89.         public override _Car ManufactureCar(CarInfo carInfo)  
  90.         {  
  91.             _Car car = null;  
  92.   
  93.             // 根据传入的型号参数创建相应的汽车实例。  
  94.             if (carInfo.Model == CarModels.ModelS)  
  95.             {  
  96.                 car = new ModelS();  
  97.             }  
  98.             else if (carInfo.Model == CarModels.Roadster)  
  99.             {  
  100.                 car = new Roadster();  
  101.             }  
  102.   
  103.             // 注意:Cybertruck 模型在这里没有被处理,所以无法由中国工厂生产!  
  104.             if (car == null)  
  105.             {  
  106.                 Debug.Log("Sorry but this factory can't manufacture this model :(");  
  107.                 return car;  
  108.             }  
  109.   
  110.             // 为汽车添加额外配置项。  
  111.             foreach (CarExtras carExtra in carInfo.Extras)  
  112.             {  
  113.                 // 根据配置项类型创建相应的装饰器,并将其应用到汽车上。  
  114.                 if (carExtra == CarExtras.DracoThruster)  
  115.                 {  
  116.                     car = new DracoThruster(car, carInfo.ExtrasNumber);  
  117.                 }  
  118.                 else if (carExtra == CarExtras.EjectionSeat)  
  119.                 {  
  120.                     car = new EjectionSeat(car, carInfo.ExtrasNumber);  
  121.                 }  
  122.                 else  
  123.                 {  
  124.                     Debug.Log("Sorry but this factory can't add this car extra :(");  
  125.                 }  
  126.             }  
  127.   
  128.             return car;  
  129.         }  
  130.     }  
  131. }
  132. using System.Collections.Generic;  
  133. using DecoratorPattern;  
  134. using DecoratorPattern.Extras;  
  135. using UnityEngine;  
  136.   
  137. namespace FactoryPattern.CarFactory  
  138. {  
  139.     public class USFactory : _CarFactory  
  140.     {  
  141.         public override _Car ManufactureCar(CarInfo carInfo)  
  142.         {  
  143.             _Car car = null;  
  144.   
  145.             if (carInfo.Model == CarModels.Cybertruck)  
  146.             {  
  147.                 car = new Cybertruck();  
  148.             }  
  149.             else if (carInfo.Model == CarModels.ModelS)  
  150.             {  
  151.                 car = new ModelS();  
  152.             }  
  153.             else if (carInfo.Model == CarModels.Roadster)  
  154.             {  
  155.                 car = new Roadster();  
  156.             }  
  157.   
  158.             if (car == null)  
  159.             {  
  160.                 Debug.Log("Sorry but this factory can't manufacture this model :(");  
  161.                 return car;  
  162.             }  
  163.   
  164.             foreach (CarExtras carExtra in carInfo.Extras)  
  165.             {  
  166.                 if (carExtra == CarExtras.DracoThruster)  
  167.                 {  
  168.                     car = new DracoThruster(car, carInfo.ExtrasNumber);  
  169.                 }  
  170.                 else if (carExtra == CarExtras.EjectionSeat)  
  171.                 {  
  172.                     Debug.Log("Sorry but this factory can't add this car extra :(");  
  173.                 }  
  174.                 else  
  175.                 {  
  176.                     Debug.Log("Sorry but this factory can't add this car extra :(");  
  177.                 }  
  178.             }  
  179.   
  180.             return car;  
  181.         }  
  182.     }  
  183. }
复制代码
建造者模式

***建造者模式(Builder Pattern)是一种创建型设计模式,它允许你分步骤构建一个复杂对象。这种模式将对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。
***主要角色

  • 产品(Product):要构建的复杂对象,它应该包含多个部分。
  • 抽象建造者(Builder):定义了构建产品的抽象接口,包括构建产品的各个部分的方法。
  • 具体建造者(Concrete Builder):实现抽象建造者接口,具体确定如何构建产品的各个部分,并负责返回最终构建的产品。
  • 指导者(Director):负责调用建造者的方法来构建产品,指导者并不了解具体的构建过程,只关心产品的构建顺序和方式。
***应用场景

  • 当创建对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
  • 当构造过程必须允许被构造的对象有不同的表示时。
  • 当需要创建一个复杂对象,但是它的部分构造过程必须有一定的顺序时。
  • 当需要在对象创建过程中进行更加精细的控制时。
***实现步骤

  • 定义产品类,表示被构建的复杂对象。
  • 定义建造者接口,包含构建对象步骤和设置属性的方法。
  • 创建具体建造者类,实现建造者接口,并实现构建对象的具体步骤。
  • 创建指导者类,负责协调构建过程,并控制建造者的顺序。
  • 在客户端代码中使用指导者构建对象。
***优点

  • 将对象的构建与表示分离,使得同样的构建过程可以创建不同的表示,增加了程序的灵活性。
  • 将复杂对象的构造代码与表示代码分开,易于维护。
  • 隐藏了对象构建的细节,使得构建代码与表示代码分离,提高了代码的可读性和可维护性。
  • 可以对不同的具体建造者进行更换和扩展
  1. using UnityEngine;  
  2.   
  3. namespace FactoryPattern.SoundFactory  
  4. {  
  5. // SoundFactoryController 类是用于管理声音系统的控制器。  
  6. // 它使用工厂方法模式来创建不同类型的音效系统实例。  
  7.     public class SoundFactoryController : MonoBehaviour  
  8.     {  
  9.         private void Start()  
  10.         {  
  11.             // 创建一个软件实现的声音系统,并播放 ID 为 1 的声音。  
  12.             ISoundSystem soundSystemSoftware = SoundSystemFactory.CreateSoundSystem(SoundSystemFactory.SoundSystemType.SoundSoftware);  
  13.             soundSystemSoftware.PlaySound(1);  
  14.   
  15.             // 创建一个硬件实现的声音系统,并播放 ID 为 2 的声音。  
  16.             ISoundSystem soundSystemHardware = SoundSystemFactory.CreateSoundSystem(SoundSystemFactory.SoundSystemType.SoundHardware);  
  17.             soundSystemHardware.PlaySound(2);  
  18.   
  19.             // 创建一个其他类型的声音系统,并播放 ID 为 3 的声音。  
  20.             ISoundSystem soundSystemOther = SoundSystemFactory.CreateSoundSystem(SoundSystemFactory.SoundSystemType.SoundSomethingElse);  
  21.             soundSystemOther.PlaySound(3);  
  22.   
  23.             // 停止播放所有之前启动的声音。  
  24.             soundSystemSoftware.StopSound(1);  
  25.             soundSystemHardware.StopSound(2);  
  26.             soundSystemOther.StopSound(3);  
  27.         }  
  28.     }  
  29. }
  30. namespace FactoryPattern.SoundFactory  
  31. {  
  32. // SoundSystemFactory 类负责创建具体的声音系统对象。  
  33.     public class SoundSystemFactory  
  34.     {  
  35.         // SoundSystemType 枚举定义了可以创建的不同类型的声音系统。  
  36.         public enum SoundSystemType  
  37.         {  
  38.             SoundSoftware, // 软件声音系统  
  39.             SoundHardware, // 硬件声音系统  
  40.             SoundSomethingElse // 其他类型的声音系统  
  41.         }  
  42.   
  43.         // CreateSoundSystem 是一个静态方法,它根据提供的类型参数返回一个新的声音系统实例。  
  44.         public static ISoundSystem CreateSoundSystem(SoundSystemType type)  
  45.         {  
  46.             ISoundSystem soundSystem = null; // 初始化为空  
  47.   
  48.             // 根据传入的类型参数选择并创建相应的声音系统实例。  
  49.             switch (type)  
  50.             {  
  51.                 case SoundSystemType.SoundSoftware:  
  52.                     soundSystem = new SoundSystemSoftware(); // 如果是软件声音系统,则创建该类的新实例  
  53.                     break;  
  54.                 case SoundSystemType.SoundHardware:  
  55.                     soundSystem = new SoundSystemHardware(); // 如果是硬件声音系统,则创建该类的新实例  
  56.                     break;  
  57.                 case SoundSystemType.SoundSomethingElse:  
  58.                     soundSystem = new SoundSystemOther(); // 如果是其他类型的声音系统,则创建该类的新实例  
  59.                     break;  
  60.                 default:  
  61.                     // 如果类型不匹配任何预定义的选项,则返回 null。  
  62.                     // 这种情况下,可能需要抛出异常或处理错误情况。  
  63.                     break;  
  64.             }  
  65.   
  66.             return soundSystem; // 返回创建的声音系统实例  
  67.         }  
  68.     }  
  69. }
  70. namespace FactoryPattern.SoundFactory  
  71. {  
  72. // 定义 ISoundSystem 接口,声明了所有具体声音系统必须实现的方法。  
  73.     public interface ISoundSystem  
  74.     {  
  75.         bool PlaySound(int soundId);  
  76.         bool StopSound(int soundId);  
  77.     }  
  78. }
  79. using UnityEngine;  
  80.   
  81. namespace FactoryPattern.SoundFactory  
  82. {  
  83.     public class SoundSystemSoftware : ISoundSystem  
  84.     {  
  85.         public bool PlaySound(int soundId)  
  86.         {  
  87.             Debug.Log($"Played the sound with id {soundId} on the software");  
  88.             return true; // 假设总是成功播放声音。  
  89.         }  
  90.   
  91.         public bool StopSound(int soundId)  
  92.         {  
  93.             Debug.Log($"Stopped the sound with id {soundId} on the software");  
  94.             return true; // 假设总是成功停止播放声音。  
  95.         }  
  96.     }  
  97. }
  98. using UnityEngine;  
  99.   
  100. namespace FactoryPattern.SoundFactory  
  101. {  
  102.     public class SoundSystemOther : ISoundSystem  
  103.     {  
  104.         public bool PlaySound(int soundId)  
  105.         {  
  106.             Debug.Log($"Played the sound with id {soundId} on some other system");  
  107.             return true;  
  108.         }  
  109.   
  110.         public bool StopSound(int soundId)  
  111.         {  
  112.             Debug.Log($"Stopped the sound with id {soundId} on some other system");  
  113.             return true;  
  114.         }  
  115.     }  
  116. }
  117. using UnityEngine;  
  118.   
  119. namespace FactoryPattern.SoundFactory  
  120. {  
  121.     public class SoundSystemHardware : ISoundSystem  
  122.     {  
  123.         public bool PlaySound(int soundId)  
  124.         {  
  125.             Debug.Log($"Played the sound with id {soundId} on the hardware");  
  126.             return true;  
  127.         }  
  128.   
  129.         public bool StopSound(int soundId)  
  130.         {  
  131.             Debug.Log($"Stopped the sound with id {soundId} on the hardware");  
  132.             return true;  
  133.         }  
  134.     }  
  135. }
复制代码
数据局部性模式

***数据局部性模式(Data Locality Pattern)是一种优化计算机程序性能的技术,其目的是最大化数据处理的速度。该模式基于这样一个事实:处理器访问距离其近的内存(如缓存)要比访问远处的存储(如RAM或硬盘)更快。数据局部性模式的核心在于组织数据结构,使得经常一起使用的数据能够被存储在物理上相近的位置。
***数据局部性的类型

  • 时间局部性(Temporal Locality):最近被访问的数据在不久的将来可能再次被访问。
  • 空间局部性(Spatial Locality):如果一个数据项被访问,那么与它相邻的数据项不久后也可能被访问。
***为什么数据局部性模式重要

  • 数据局部性模式对于提升程序性能至关重要,尤其是在处理大量数据或高性能计算任务时。通过优化数据存储,可以减少缓存未命中(Cache Miss)的情况,从而提高程序的运行效率
  1. using UnityEngine;  
  2.   
  3. namespace FactoryPattern.UIFactory  
  4. {  
  5.     public class UIFactoryController:MonoBehaviour  
  6.     {  
  7.         private IUIButton _button;  
  8.         private IUITextField _textField;  
  9.   
  10.         private void Start()  
  11.         {  
  12.             // 选择你想要使用的工厂  
  13.             IUIFactory factory = GetSelectedFactory();  
  14.   
  15.             // 使用选定的工厂创建UI元素  
  16.             _button = factory.CreateButton();  
  17.             _textField = factory.CreateTextField();  
  18.   
  19.             // 渲染UI元素  
  20.             _button.Render();  
  21.             _textField.Render();  
  22.         }  
  23.   
  24.         private IUIFactory GetSelectedFactory()  
  25.         {  
  26.             // 这里可以根据某些条件选择不同的工厂  
  27.             return new ModernIUIFactory(); // 或者 new RetroGuiFactory();        }  
  28.     }  
  29. }
  30. namespace FactoryPattern.UIFactory  
  31. {  
  32.     public interface IUIButton  
  33.     {  
  34.         void Render();  
  35.     }  
  36.   
  37.     public interface IUITextField  
  38.     {  
  39.         void Render();  
  40.     }  
  41. }
  42. using UnityEngine;  
  43.   
  44. namespace FactoryPattern.UIFactory  
  45. {  
  46.     public class ModernUIButton : MonoBehaviour, IUIButton  
  47.     {  
  48.         public void Render()  
  49.         {  
  50.             Debug.Log("Rendering a modern button.");  
  51.         }  
  52.     }  
  53. }
  54. using UnityEngine;  
  55.   
  56. namespace FactoryPattern.UIFactory  
  57. {  
  58.     public class ModernUITextField : MonoBehaviour, IUITextField  
  59.     {  
  60.         public void Render()  
  61.         {  
  62.             Debug.Log("Rendering a modern text field.");  
  63.         }  
  64.     }  
  65. }
  66. using UnityEngine;  
  67.   
  68. namespace FactoryPattern.UIFactory  
  69. {  
  70.     public class RetroUIButton : MonoBehaviour, IUIButton  
  71.     {  
  72.         public void Render()  
  73.         {  
  74.             Debug.Log("Rendering a retro button.");  
  75.         }  
  76.     }  
  77. }
  78. using UnityEngine;  
  79.   
  80. namespace FactoryPattern.UIFactory  
  81. {  
  82.     public class RetroUITextField : MonoBehaviour, IUITextField  
  83.     {  
  84.         public void Render()  
  85.         {  
  86.             Debug.Log("Rendering a retro text field.");  
  87.         }  
  88.     }  
  89. }
  90. namespace FactoryPattern.UIFactory  
  91. {  
  92.     public interface IUIFactory  
  93.     {  
  94.         IUIButton CreateButton();  
  95.         IUITextField CreateTextField();  
  96.     }  
  97. }
  98. using UnityEngine;  
  99.   
  100. namespace FactoryPattern.UIFactory  
  101. {  
  102.     public class ModernIUIFactory : IUIFactory  
  103.     {  
  104.         public IUIButton CreateButton()  
  105.         {  
  106.             return new GameObject("ModernButton").AddComponent<ModernUIButton>();  
  107.         }  
  108.   
  109.         public IUITextField CreateTextField()  
  110.         {  
  111.             return new GameObject("ModernTextField").AddComponent<ModernUITextField>();  
  112.         }  
  113.     }  
  114. }
  115. using UnityEngine;  
  116.   
  117. namespace FactoryPattern.UIFactory  
  118. {  
  119.     public class RetroIUIFactory : IUIFactory  
  120.     {  
  121.         public IUIButton CreateButton()  
  122.         {  
  123.             return new GameObject("RetroButton").AddComponent<RetroUIButton>();  
  124.         }  
  125.   
  126.         public IUITextField CreateTextField()  
  127.         {  
  128.             return new GameObject("RetroTextField").AddComponent<RetroUITextField>();  
  129.         }  
  130.     }  
  131. }
复制代码
[code]//在for循环中遍历了指针,但指针又指向另外的内存,这就引发了缓存的低命中率private void Update(){    for(int i=0;i
您需要登录后才可以回帖 登录 | 立即注册