单例模式

 

定义:确保一个类只能有一个实例,并提供一个全局访问点

笔记:一个实例。

 

 

懒汉式单例模式

“双重检查加锁”

package com.tj.singleton.threadsafe.dcl; //double-checked locking //Danger! This implementation of Singleton not //guaranteed to work prior to Java 5 public class Singleton { private volatile static Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }  

 

饿汉式单例模式

package com.tj.singleton.threadsafe.eager; public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return uniqueInstance; } } 

 

以下文章讲解比较详细

http://www.cnblogs.com/QinBaoBei/archive/2010/05/07/1729376.html

 

你可能感兴趣的:(java,null,Class,2010)