【Unity3D与23种设计模式】策略模式(Strategy)

时间:2023-03-09 22:32:54
【Unity3D与23种设计模式】策略模式(Strategy)

GoF中定义:

“定义一组算法,并封装每个算法,让它们之间可以彼此交换使用。

策略模式让这些算法在客户端使用它们时能更加独立。”

游戏开发过程中

不同的角色会有不同的属性计算方法

初级解决方法便是:if else,不够再来几个if else

高级点儿的就用switch case配合enum

对于小型项目或者快速开发验证用的项目而言,这么做是没问题的

但是开发规模或产品化项目时,最好还是选择策略模式

在策略模式中,

算法中的每一个都应该独立出来

将计算细节加以封装

客户端只要根据情况来选择对应的算法即可

至于具体的计算方式及规则,客户端便不需理会

using UnityEngine;

public abstract class Strategy {
public abstract void AlgorithmInterface();
} public class StrategyA : Strategy {
public override void AlgorithmInterface()
{
Debug.Log("StrategyA.AlgorithmInterface");
}
} public class StrategyB : Strategy
{
public override void AlgorithmInterface()
{
Debug.Log("StrategyB.AlgorithmInterface");
}
} public class StrategyC : Strategy
{
public override void AlgorithmInterface()
{
Debug.Log("StrategyC.AlgorithmInterface");
}
} public class Context {
Strategy m_Strategy = null; public void SetStrategy(Strategy theStrategy) {
m_Strategy = theStrategy;
} public void ContextInterface() {
m_Strategy.AlgorithmInterface();
}
}

策略模式与状态模式非常相似

在GoF中,两者都被归类在行为模式(Behavioral Patterns)分类下

都是由一个Context类来维护对象引用

并借此调用提供功能的方法

不同点在于:

State是一群状态中进行切换,状态之间有对应和链接的关系

Strategy则是由一群没有任何关系的类所组成,不知彼此的存在

文章整理自书籍《设计模式与游戏完美开发》 菜升达 著