单子模式比较容易理解,一般使用的时候就是让一个类 只能创建一个类实例
- clsss Singleton{
- //要实例的对象
- //限制
- private Singleton(){}
- //这里必须是静态
- private static Singleton singleton = null;
- public static Singleton CreateInstance{
- get{
- if(singleton==null){
- singleton = new Singleton();
- }
- return singleton;
- }
- }
- }
示例2 .
相比之下上面的编写方式比较优秀点,因为只有当使用时才创建
- clsss Singleton{
- //要实例的对象
- //限制
- private Singleton(){}
- //这里必须是静态
- private static Singleton singleton = new Singleton();
- public static Singleton CreateInstance{
- get{
- return singleton;
- }
- }
- }