using UnityEngine;
using System.Collections;
namespace TemplateMethodPatternExample1
{
public class TemplateMethodPatternExample1 : MonoBehaviour
{
void Start()
{
Hoagie cust12Hoagie = new OmnivoreHoagie();
cust12Hoagie.Makehamburger();
Hoagie cust13Hoagie = new VeggieHoagie();
cust13Hoagie.Makehamburger();
}
}
public abstract class Hoagie
{
public void Makehamburger()
{
Debug.Log("做一个汉堡包");
CutBun();
if (CustomerWantsMeat())
{
AddMeat();
}
if (CustomerWantsCheese())
{
AddCheese();
}
if (CustomerWantsVegetables())
{
AddVegetables();
}
if (CustomerWantsCondiments())
{
AddCondiments();
}
WrapTheHoagie();
}
protected abstract void AddMeat();
protected abstract void AddCheese();
protected abstract void AddVegetables();
protected abstract void AddCondiments();
protected virtual bool CustomerWantsMeat() { return true; } // 告诉厨师要不要做
protected virtual bool CustomerWantsCheese() { return true; }
protected virtual bool CustomerWantsVegetables() { return true; }
protected virtual bool CustomerWantsCondiments() { return true; }
protected void CutBun()
{
Debug.Log("面包切好了");
}
protected void WrapTheHoagie()
{
Debug.Log("打包好了");
}
}
//啥都吃
public class OmnivoreHoagie : Hoagie
{
protected override void AddMeat()
{
Debug.Log("加肉");
}
protected override void AddCheese()
{
Debug.Log("加芝士");
}
protected override void AddVegetables()
{
Debug.Log("加生菜");
}
protected override void AddCondiments()
{
Debug.Log("加沙拉");
}
}
//素食主义
public class VeggieHoagie : Hoagie
{
protected override void AddMeat()
{
}
protected override void AddCheese()
{
}
protected override void AddVegetables()
{
Debug.Log("加生菜");
}
protected override void AddCondiments()
{
Debug.Log("加沙拉");
}
//告诉厨师不需要做肉和芝士了
protected override bool CustomerWantsMeat() { return false; }
protected override bool CustomerWantsCheese() { return false; }
}
其实就是子类重写父类的方法