第一节:泛型在单例游戏基类中的简单运用
运用知识点
泛型:单例模式
作用:
减少单例模式重复代码的书写
具体实例
这是使用泛型前的代码
public class Test { void Main() { GameManager.GetInstance(); GameManager.GetInstance(); } } public class GameManager { private static GameManager instance; public static GameManager GetInstance() { if(instance == null) { instance = new GameManager(); } return instance; } } public class ObjectManager { private static ObjectManager instance; public static ObjectManager GetInstance() { if (instance == null) { instance = new ObjectManager(); } return instance; } }
运用泛型的单例模式基类
public class Test { void Main() { GameManager.GetInstance(); ObjectManager.GetInstance(); } } public class BaseManager<T > where T:new() { private static T instance; public static T GetInstance() { if (instance == null) { instance = new T(); } return instance; } } public class GameManager: BaseManager<GameManager> { } public class ObjectManager:BaseManager<ObjectManager> { }
两者实现效果相同