标签:单例模式封装
很多时候我们需要A脚本调用B脚本里面的属性什么的,这个时候我们可以在这个需要被调用属性脚本里面写一个单例模式。可项目大了需要被调用的脚本也就会很多,这个时候我们要是还像以前那样每个需要被调用的脚本里面就写一个单例模式,那样就太麻烦了。所以这里我们可以封装下这个单例模式。
写一个类:
public class Singleton<T> where T :new(){
protected static T sInstance = default(T);
public static T GetInstance(){
if (sInstance == null) {
sInstance = new T();
}
return sInstance;
}
}
然后在需要调用单例的地方写成:
public class EventCenter : Singleton<EventCenter>{
}
这样我们这个EventCenter这个脚本就是单例了。
本文出自 “酷酷小乔” 博客,请务必保留此出处http://5152481.blog.51cto.com/5142481/1686353
标签:单例模式封装
原文地址:http://5152481.blog.51cto.com/5142481/1686353