C# 与JSE的单例设计模式的区别

 
 
//1.饿汉式单例类(类加载时就初始化)

public class Singleton {
    //私有的类成员常量
    private static final Singleton singleton=new Singleton();
    //私有的默认构造方法,此类不能被继承
    private Singleton(){}
    //静态工厂方法
    public static Singleton getInstance(){
      return singleton;
  }
}

// 2.懒汉式单例类(第一次调用才初始化,延迟) 

 public class Singleton {
private  static Singleton singleton=null;
//私有的默认构造方法,此类不能被继承
private Singleton(){}
//同步,静态工厂方法,返回此类的唯一实例
public synchronized static Singleton getInstance(){
    if(singleton==null){
       singleton=new Singleton();
 }
         return singleton;
    }
}

3.对2的懒汉式的另外一种改进 

public class Singleton {
private volatile static Singleton singleton = null;

// 私有的默认构造方法,此类不能被继承
private Singleton() {
}
// 静态工厂方法,返回此类的唯一实例
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}


 //4.登记式单例类 
   // 登记式单例类是为了克服饿汉式单例类和懒汉式单例类不可继承的缺点而设计的.
package com.jse.singleton;

import java.util.HashMap;

public class RegSingleton {
private static HashMap registry=new HashMap();
/**静态代码块
        *静态代码块优先于主方法执行,而在类中定义的静态代码会优先于构造块执行,而且
        *不管产生多少对象,静态代码块只执行一
        */
static{
RegSingleton singleton=new RegSingleton();
registry.put(singleton.getClass().getName(), singleton);
}

protected RegSingleton(){}

public static RegSingleton getInstance(String name){
if(name==null){
name="com.jse.singleton.RegSingleton";
}
if(registry.get(name)==null){
try {
registry.put(name, Class.forName(name).newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return (RegSingleton) registry.get(name);
}
}

  

//第一种:最简单,但没有考虑线程安全,在多线程时可能会出问题
public class Singleton
{
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            _instance = new Singleton();
        }
        return _instance;
    }
}
//第二种:考虑了线程安全,锁定当对象
public class Singleton
{
    private volatile static Singleton _instance = null;
    private static readonly object lockHelper = new object();
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            lock(lockHelper)
            {
                if(_instance == null)
                     _instance = new Singleton();
            }
        }
        return _instance;
    }
}

//第三种:可能是C#这样的高级语言特有的,实在懒得出奇
public class Singleton
{
    private Singleton(){}
    public static readonly Singleton instance = new Singleton();
}  

 

你可能感兴趣的:(JSE/C#)