Singleton
来源:互联网 发布:淘宝网红安娜 编辑:程序博客网 时间:2024/05/01 18:10
从今天开始正式学习C#设计模式:
第一章: Singleton模式(单列模式)
该模式为创建形模式,(Creational)
Intent:
确保在系统中只有一个实例,并提供一个该实例的全局访问点(这个责任应该是类设计者的,而非使用者责任)
单线程情况下:
public class Thread
...{
private static Thread _Instance = null;
private Thread()
...{
}
public static Thread Instance
...{
get
...{
if (_Instance != null)
...{
_Instance = new Thread();
}
return _Instance;
}
}
}
...{
private static Thread _Instance = null;
private Thread()
...{
}
public static Thread Instance
...{
get
...{
if (_Instance != null)
...{
_Instance = new Thread();
}
return _Instance;
}
}
}
多线程情况下:
public class MultiThread
...{
private static volatile MultiThread _Instance = null;
private static object lockHelper = new object();
private MultiThread()
...{ }
public static MultiThread Intance
...{
get
...{
if (_Instance != null)
...{
lock (lockHelper)
...{
if (_Instance != null)
...{
_Instance = new MultiThread();
}
}
}
return _Instance();
}
}
}
...{
private static volatile MultiThread _Instance = null;
private static object lockHelper = new object();
private MultiThread()
...{ }
public static MultiThread Intance
...{
get
...{
if (_Instance != null)
...{
lock (lockHelper)
...{
if (_Instance != null)
...{
_Instance = new MultiThread();
}
}
}
return _Instance();
}
}
}
另外一种比较好的方法(但该方法不支持在创建对象时使用参数)
public class AnotherMethod
...{
public static readonly AnotherMethod Intance = new AnotherMethod();
private AnotherMethod()
...{ }
}
...{
public static readonly AnotherMethod Intance = new AnotherMethod();
private AnotherMethod()
...{ }
}
注意:
C#中,静态构造器只在静态属性和方法之前执行,因为该方法是RunTime调用,所以无法传参.
扩展:
1,将只能有1个实例,扩展到只能有N个实例子,例如对象池的实现
2,将new 构造器的调用转移到其他类中,例如多个类协同工作环境中,某个局部环境只需要拥有某个类的一个实例。
- Singleton
- Singleton
- singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Vbs脚本编程简明教程之四
- 女人,怎样才算解放自己
- 女子感悟
- 解决AJAX中使用UpdatePanel后再用Response.Write();等无法弹出对话框问题
- ActiveReports工作总结6——使用子报表
- Singleton
- Vbs脚本编程简明教程之五
- ActiveReports工作总结7——常用一览表印刷
- Vbs脚本编程简明教程之六
- ActiveReports工作总结8——用代码控制布局
- 怎样处理乱码的问题
- 3R女人能获得幸福吗?
- ActiveReports工作总结9——打印参数设置
- 女人要奋力抛弃爱情魔鬼