设计模式之单例模式精简写法解惑
单例模式介绍
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式的精简写法
public class Singleton<T> where T : new()
{
public static T Instance
{
get { return SingletonCreate.instance; }
}
class SingletonCreate
{
internal static readonly T instance = new T();
}
}
疑问解析:
Singleton<T>:泛型
where T : new():类型参数(T)必须具有无参数的公共构造函数
static readonly T:顺便了解下const 和static readonly的区别
const和static readonly的确很像:通过类名而不是对象名进行访问,在程序中只读等等。在多数情况下可以混用。
二者本质的区别在于,const的值是在编译期间确定的,因此只能在声明时通过常量表达式指定其值。而static readonly是在运行时计算出其值的,所以还可以通过静态构造函数来赋值。
static readonly int [] constIntArray = new int[] {1, 2, 3};
不可以换成const。new操作符是需要执行构造函数的,所以无法在编译期间确定,虽然看起来1,2,3的数组的确就是一个常量。
void SomeFunction()
{
const int a = 10;
...
}
不可以换成readonly,readonly只能用来修饰类的field,不能修饰局部变量,也不能修饰property等其他类成员。
static readonly需要注意的一个问题是,对于一个static readonly的Reference类型,只是被限定不能进行赋值(写)操作而已。而对其成员的读写仍然是不受限制的。
public static readonly MyClass myins = new MyClass();
myins.SomeProperty = 10; //正常
myins = new MyClass(); //出错,该对象是只读的
参考文章:
http://www.cnblogs.com/webabcd/archive/2007/02/10/647140.html
http://www.cnblogs.com/smalldust/archive/2008/04/08/167494.html

浙公网安备 33010602011771号