单例模板

/*
    有人可能会问,实现singleton的代码并不多,我们没必要搞这么一个机制来做代码复用吧?
    的确,我们复用的代码并不是很多,但是,我想代码复用的目的不仅仅是减少代码量,其最重要的目的还是在于保持行为的一致性。
    以便于使用与维护。(用函数替换代码段便是一个很好的例子)。 
	对于这里的singleton类来讲,如果不做这个设计,我们在每个具体的singleton类内部实现其singleton机制,那么可能出现的问题是:
	
	1. 很难保证其接口的一致性
	张三写了一个singleton类,全局访问函数是Instance, 
	李四也写了一个Singleton类,全局访问函数可能就是GetInstance了.
	我们并没有一个健壮的机制来保证接口的一致性,从而导致了使用的混乱性。

	2. 不易维护
	Singleton创建实例有两种:一种为lazy initialization, 一种就是early initialization, 
	假如开始的实现是所有的singleton都用lazy initialization, 
	突然某种需求要求你用early initialization,你的噩梦就开始了,你不得不重写每一个singleton类。

	而用了singleton模板基类这种机制,以上问题就不会存在,我们得到的不仅仅是节约几行代码。
 */

/// <summary>
/// Singleton模板基类
/// </summary>

using System;

/// <summary>
/// 这里,我们把为了支持Singleton功能的代码提到一个Singleton<T>的类模板当中,
///	任何需要成为Singlton的类,只需从其派生便自然获得Singleton功能。
/// </summary>
using System.Reflection;


public class Singleton<T> where T: new()
{
	/*
	为了支持模板类中的new()constraint,我们不得不把作为具体singleton类的派生类的构造函数作为public.
	这就导致我们无法在编译期阻止用户自行new出第二个,但我们可以在运行期来进行检查进而保证其实例的单一性,
	这就是这singleton基类构造函数的作用
	 */

	protected Singleton()
	{
		UnityEngine.Debug.Assert(null == instance);
	}

	protected static T instance = new T();

	public static T GetInstance
	{
		get{return instance;}
	}
}

public class SingletonRef<T>
{
//	BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);  
//
//	Type t = typeof(T); 
//
//	MethodInfo[] mi = t.GetMethods(flags); 
//
//	protected static T instance = (T)Activator.CreateInstance(t);  
//
//	public static T GetInstance
//	{
//		get { return instance; }
//	}
}

// Concrete singleton class, derived from Singleton<T>
public class ExampleSingleton: Singleton<ExampleSingleton>
{
	// since there is no "freind class" in C#, we have to make
	// this contructor public to support the new constraint.
	public ExampleSingleton(){}
	
	// This class's real functionalities
	public void Write()
	{
		Console.WriteLine("Hello, World!");
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值