如果你正在学习设计模式,或者想学习设计模式,这篇文章可能对你有用;如果不是,那你就只有路过了。。
Singleton是设计模式中比较特殊的一种,也是比较浅的一种,闲来无事,写出来。
希望对各位有用,顺便也是自己温习一下。
这篇文章主要只是讲解了代码中一些不是特别容易懂的地方,关于深层的东西,本人没资力,所以无法写出。
Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点。
Singleton的主要就是为了限制每个类仅仅只有一个实例。
说多的理论东西可能还会让你头晕。。如果上面的那些话看着似懂非懂。还是看代码比较好。。 代码一: - public sealed class Singleton
- {
- static Singleton instance=null;
- Singleton()
- {
- }
- public static Singleton Instance
- {
- get
- {
- if (instance==null)
- {
- instance = new Singleton();
- }
- return instance;
- }
- }
- }
复制代码
类前面的sealed是防止该类被继承,从而破坏该类只能一个实例的要求。
定义了一个静态的Singleton类型变量。
给了一个只读属性Instance 返回类型为Singleton
首先判断定义的instance是不是为空,就是验证有没有被实例化过。
如果有,返回之前实例化的那个,否则重新实例化一个新对象。
问题:此代码对于多线程的程序不是很好。
当两个线程同时判断if (instance==null)时。
可能同时创建两个新对象。
代码二:- public sealed class Singleton
- {
- static Singleton instance=null;
- static readonly object padlock = new object();
- Singleton()
- {
- }
- public static Singleton Instance
- {
- get
- {
- lock (padlock)
- {
- if (instance==null)
- {
- instance = new Singleton();
- }
- return instance;
- }
- }
- }
- }
复制代码 这段代码借助了一个另一个对象来达到安全线程的效果。
当访问Instance属性时。
锁定当前线程,这样就不会出现两个线程同时创建的结果。。
提示:为什么要借助另一个对象?。因为如果这个时候lock(instance)
这个时候 instance 为空的话,会报错。
代码三:- public sealed class Singleton
- {
- static Singleton instance=null;
- static readonly object padlock = new object();
- Singleton()
- {
- }
- public static Singleton Instance
- {
- get
- {
- if (instance==null)
- {
- lock (padlock)
- {
- if (instance==null)
- {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
- }
- }
复制代码 这段代码首先判断空,然后锁定,由于多线程同时访问的机率就很小,而且不是每次都锁定线程。所以此方法不错。
问题:这段代码在Java中无法工作。
代码四:- public sealed class Singleton
- {
- static readonly Singleton instance=new Singleton();
- // Explicit static constructor to tell C# compiler
- // not to mark type as beforefieldinit
- static Singleton()
- {
- }
- Singleton()
- {
- }
- public static Singleton Instance
- {
- get
- {
- return instance;
- }
- }
- }
复制代码 这段代码它依赖公共语言运行库来初始化变量,所以执行控制的权力比较小。
而且当调用类中其他方法时,会实例化对象。
问题:无法达到延时实例化。
代码五:- public sealed class Singleton
- {
- Singleton()
- {
- }
- public static Singleton Instance
- {
- get
- {
- return Nested.instance;
- }
- }
-
- class Nested
- {
- // Explicit static constructor to tell C# compiler
- // not to mark type as beforefieldinit
- static Nested()
- {
- }
- internal static readonly Singleton instance = new Singleton();
- }
- }
复制代码
这里,初始化工作由Nested类的一个静态成员来完成,这样就实现了延迟初始化。
只要不访问Instance属性,访问Singleton类中其他方法都不会初始化对象。值得推荐。
OK。五段代码说完了。。自己的理解。基本没什么错误吧。。
希望对各位初学者有点用处了。。^^
代码出处:http://www.yoda.arachsys.com/csharp/singleton.html
[ 本帖最后由 传说中的Kid 于 2006-12-26 16:45 编辑 ] |