一、概述
单例模式(Singleton),保证一个类仅有一个实例,并提供一个访问它的全局访问点 。
二、UML图示
三、代码实现
1、singleton类
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance(){
if(null == instance){
instance = new Singleton();
}
return instance;
}
}
2、测试
public class Test {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
Singleton singleton1 = Singleton.getInstance();
System.out.println(singleton == singleton1);
}
}
输出:
true
3、多线程下的singleton类
public class Singleton {
private static Singleton instance;
//进程辅助对象
public static Object syncRoot = new Object();
private Singleton() {
}
public static Singleton getInstance(){
if(null == instance){
synchronized (syncRoot){
if(null == instance){
instance = new Singleton();
}
}
}
return instance;
}
}
4.单例模式的多种写法
/**
* 1.饿汉式:线程安全,耗费资源
*/
class HugerSingleton1 {
//该对象的引用不可修改
private static final HugerSingleton1 ourInstance = new HugerSingleton1();
public static HugerSingleton1 getInstance() {
return ourInstance;
}
private HugerSingleton1() {}
}
/**
* 2.饿汉式:在静态代码块实例对象
*/
class HugerSingleton2 {
private static HugerSingleton2 ourInstance;
static {
ourInstance = new HugerSingleton2();
}
public static HugerSingleton2 getInstance() {
return ourInstance;
}
private HugerSingleton2() {}
}
/**
* 3.懒汉式:非线程安全
*/
class Singleton1 {
private static Singleton1 ourInstance;
public static Singleton1 getInstance() {
if (null == ourInstance) {
ourInstance = new Singleton1();
}
return ourInstance;
}
private Singleton1() {}
}
/**
* 4.线程安全的懒汉式:给方法加锁,每次都枷锁,耗时
*/
class Singleton2 {
private static Singleton2 ourInstance;
public synchronized static Singleton2 getInstance() {
if (null == ourInstance) {
ourInstance = new Singleton2();
}
return ourInstance;
}
private Singleton2() {}
}
/**
* 5.线程安全的懒汉式:双重检查锁(同步代码块),代码较复杂
*/
class Singleton3 {
private static Singleton3 ourInstance;
public static Singleton3 getInstance() {
if (null == ourInstance) {
synchronized (Singleton3.class) {
if (null == ourInstance) {
ourInstance = new Singleton3();
}
}
}
return ourInstance;
}
private Singleton3() {}
}
/**
* 6.线程安全的懒汉式:静态内部类(第一推荐)
*/
class Singleton4 {
static class SingletonHolder {
private static Singleton4 ourInstance = new Singleton4();
}
public static Singleton4 getInstance() {
return SingletonHolder.ourInstance;
}
private Singleton4() {
}
}
注:参考文献《大话设计模式》程杰著。