学习过的东西经常忘记,最好能自己在事后回顾一下,并写出具体的实现代码,这样才能加深记忆。
最近学习过单例模式,包括惰性加载方式、非惰性加载方式以及泛型方式实现。下面回顾一下代码。
1、非惰性加载、非泛型方式
-
-
-
- public class Singleton
- {
- static readonly Singleton instance = new Singleton();
-
- static Singleton()
- {
- }
-
- public static
Singleton Instance
- {
- get
- {
- return instance;
- }
- }
- }
2、惰性加载、非泛型方式:避免了线程安全问题
-
-
-
- public class Singleton
- {
- static Singleton()
- {
- }
-
- public static Singleton Instance
- {
- get
- {
- return SingletonInnerClass.singleton;
- }
- }
-
-
-
-
-
class SingletonInnerClass
- {
- static
SingletonInnerClass() { }
- public static Singleton singleton = new Singleton();
- }
- }
3、非惰性加载、泛型方式
-
-
-
- public class Singleton<T> where T:new()
- {
- static readonly T instance = new T();
-
- static Singleton()
- {
- }
-
- public T Instance
- {
- get
- {
- return instance;
- }
- }
- }
4、惰性加载、泛型实现方式
-
-
-
- public class Singleton<T> where T:new()
- {
- static Singleton()
- {
- }
-
- public static T Instance
- {
- get
- {
- return SingletonInnerClass.singleton;
- }
- }
-
-
-
-
- class SingletonInnerClass
- {
- static SingletonInnerClass() { }
- internal static T singleton = new T();
- }
- }
- 各个版本的实现都有自己的优势,大家可以根据自己的需要自行选择,关于非泛型版本之间效率和安全的比较,大家可参考:http://rhx520.blog.163.com/blog/static/2998792020081122102444743/
|