【策略模式】官方一點的解釋是定義一組算法,將每個算法都封裝起來,並且使它們之間可以互換。有點難理解,但是呢,仔細一看。。。。。。這個勉強算是switch case、if else的延伸?。。。。。。而且爲什麼我覺得和命令模式好像啊~
上代碼:
using UnityEngine;
/// <summary>
/// 設計模式——策略模式
/// </summary>
public class DesignMode_Strategy : MonoBehaviour {
// Use this for initialization
void Start () {
ITLion lion = new ITLion();
lion.SetDemand(new DemandOne());
lion.Coding();
lion.SetDemand(new DemandTwo());
lion.Coding();
}
}
/// <summary>
/// 需求父類
/// </summary>
public abstract class Demand
{
public abstract void DemandType();
public abstract void Achieve();
}
public class DemandOne : Demand
{
public override void Achieve()
{
Debug.Log("加班到9點就行");
}
public override void DemandType()
{
Debug.Log("小需求");
}
public DemandOne()
{
DemandType();
}
}
public class DemandTwo : Demand
{
public override void DemandType()
{
Debug.Log("大需求");
}
public override void Achieve()
{
Debug.Log("加班到12點");
}
public DemandTwo()
{
DemandType();
}
}
/// <summary>
/// 工程師類
/// </summary>
public class ITLion {
public Demand mDemand;
/// <summary>
/// 得到需求
/// </summary>
/// <param name="demand"></param>
public void SetDemand(Demand demand)
{
mDemand = demand;
}
/// <summary>
/// 根據需求類型決定加班到幾點
/// </summary>
public void Coding()
{
mDemand.Achieve();
}
}
運行截圖:
也沒有大佬給我指正一下麼?…悶頭學習中…