簡單工廠模式又稱為靜態工廠模式,其實就是根據傳入參數創建對應具體類的實例并返回實例對象,這些類通常繼承至同一個父類,該模式專門定義了一個類來負責創建其他類的實例。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;//父類接口
public interface Animal
{void Eat();
}//貓子類
public class Cat : Animal
{public void Eat(){Debug.Log("貓");}
}//狗子類
public class Dog : Animal
{public void Eat(){Debug.Log("狗");}
}
?這就是工廠類,提供一個方法創建具體類的實例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Factory
{public static Animal CreatAnimal(string animal){Animal animalObj = null;switch (animal){case "cat":animalObj = new Cat();break;case "dog":animalObj = new Dog();break;}return animalObj;}
}
優點:將對象的創建于使用分離,創建完全交給工廠類來實現。
缺點:違反了開閉原則(即對修改關閉,對拓展開放),當有新的具體類需要創建時都需要修改工廠類中的創建方法,多增加判斷。?