Unity3d之設計模式—工廠方法
廠方法與簡單工廠最大的區別,在於工廠方法將工廠進行了抽象,將實現邏輯延遲到工廠的子類。
using UnityEngine;
// 食物抽象類 public abstract class Food { public abstract void MenuFood(); }
// 西紅柿炒雞蛋這道菜 public class Tomato:Food { public override void MenuFood() { Debug.Log("西紅柿菜"); } }
//辣椒炒飯 public class Pepper : Food { public override void MenuFood() { Debug.Log("辣椒炒飯"); } }
// 抽象工廠類 public abstract class FoodFactory { public abstract Food CreateFoodFactory(); }
// 西紅柿工廠類 public class TomatoFactory:FoodFactory { public override Food CreateFoodFactory() { return new Tomato(); } }
//辣椒炒飯工廠類 public class PepperFactory : FoodFactory { public override Food CreateFoodFactory() { return new Pepper(); } }
// 客戶端呼叫
using UnityEngine;
public class Client : MonoBehaviour { void Start () { // 初始化做菜的兩個工廠() FoodFactory tomatoFactory = new TomatoFactory(); FoodFactory pepperFactory = new PepperFactory();
// 開始做西紅柿 Food tomato = tomatoFactory.CreateFoodFactory(); tomato.MenuFood();
//開始做辣椒炒飯 Food pepper = pepperFactory.CreateFoodFactory(); pepper.MenuFood(); } }