策略模式
介绍
设计模式 | 定义 | 案例 | 问题堆积在哪里 | 解决办法 |
策略模式 | 对算法进现封装,抽象 如:IF elseIF 一大堆 可以配合工厂模式使用 | 炼丹炉里做饭 要求 菜谱 和 食材可配置 | 问题在可配置 菜谱 | 封装菜谱 然后抽象菜谱,为了统一使用方法 |
类图
CaiPuBase 抽象菜谱
CaiPuA 菜谱A
CaiPuB 菜谱B
CaiPuC 菜谱C
LianDanLu 炼丹炉
代码
CaiPuBase
using System.Collections.Generic;
/// <summary>
/// 菜谱
/// </summary>
public abstract class CaiPuBase
{
public abstract string Create(List<string> foodList);
}
CaiPuA
using System.Collections.Generic;
public class CaiPuA : CaiPuBase
{
string funName = "炒";
public override string Create(List<string> elementList)
{
string result;
result = funName + ":";
foreach (var item in elementList)
{
result += item;
}
return result;
}
}
CaiPuB
using System.Collections.Generic;
public class CaiPuB : CaiPuBase
{
string funName = "蒸";
public override string Create(List<string> elementList)
{
string result;
result = funName + ":";
foreach (var item in elementList)
{
result += item;
}
return result;
}
}
CaiPuC
using System.Collections.Generic;
public class CaiPuC : CaiPuBase
{
string funName = "煮";
public override string Create(List<string> elementList)
{
string result;
result = funName + ":";
foreach (var item in elementList)
{
result += item;
}
return result;
}
}
LanDanLu
using System.Collections.Generic;
/// <summary>
/// 炼丹炉
/// </summary>
public class LianDanLu
{
public string GetFood(CaiPuBase caiPu, List<string> elementList)
{
return caiPu.Create(elementList);
}
}
测试代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestCL : MonoBehaviour
{
void Start()
{
LianDanLu ldl = new LianDanLu();
{
List<string> list = new List<string>
{
"萝卜",
"鸡蛋"
};
string food = ldl.GetFood(new CaiPuA(), list);
Debug.Log(food);
}
{
List<string> list = new List<string>
{
"萝卜",
"鸡蛋"
};
string food = ldl.GetFood(new CaiPuB(), list);
Debug.Log(food);
}
{
List<string> list = new List<string>
{
"萝卜",
"鸡蛋"
};
string food = ldl.GetFood(new CaiPuC(), list);
// show
Debug.Log(food);
}
}
}
结果
总结
函数抽象出变量
类抽象出行为
单一的模式很简单 ,难的是从整体出发一步一模式,把细节一直推迟到配置文件/Excel。
多做进行大项目的开发还是很有好处的!