设计模式之单例模式

单利模式一共包含懒汉式 饿汉式 双重检查加锁 。

/**

* 懒汉式

* @author guang09080908

*/

public class Singleton {

private static Singleton instance = null;

private Singleton(){}

public synchronized static Singleton getInstance()

{  

if(instance == null)

instance = new Singleton();

return instance;

}

}

/**

* 饿汉式

* @author guang09080908

*/

public class Singleton {

private static Singleton instance = new Singleton();

private Singleton(){}

public static Singleton getInstance()

{  

return instance;

}

}

/**

* 双重检查加锁

* @author guang09080908

*/

public class Singleton {

private volatile static Singleton instance = null;

private Singleton(){}

public static Singleton getInstance()

{

if(instance == null)

{

synchronized (Singleton.class)

{

if(instance == null)

instance = new Singleton();

}

}

return instance;

}

}

你可能感兴趣的:(设计模式之单例模式)