单例设计模式
Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点。
(1) 将采用单例设计模式的类的构造方法私有化(采用private修饰)。
(2) 在其内部产生该类的实例化对象,并将其封装成private static类型。
(3) 定义一个静态方法返回该类的实例。
饿汉式天生就是线程安全的,可以直接用于多线程而不会出现问题,懒汉式本身是非线程安全的
饿汉式(线程安全 但效率比较低 )
public class Singleton_1 {
//饿汉式
private Singleton_1() {
}
private static Singleton_1 instance = new Singleton_1();
public static Singleton_1 GetInstance() {
return instance;
}
}
懒汉式
public class Singleton_2 {
// 懒汉式
private Singleton_2() {
}
private static Singleton_2 instance = null;
public static Singleton_2 getInstance(){
if(instance == null)
instance = new Singleton_2();
return instance;
}
}
懒汉式(线程安全)
public class Singleton_3 {
// 线程安全的(双重检查锁定)
private Singleton_3() {
}
private volatile static Singleton_3 instance = null;
//同步方法
public static synchronized Singleton_3 GetInstance() {
if (instance == null)
instance = new Singleton_3();
return instance;
}
//同步代码块
public static Singleton_3 GetInstanceBlock() {
if (instance == null) {
synchronized (Singleton_3.class) {
if (instance == null)
instance = new Singleton_3();
}
}
return instance;
}
}
静态代码块
public class Singleton_4 {
// 利用静态代码块
private Singleton_4() {
}
private static class SingletonHolder {
private final static Singleton_4 instance = new Singleton_4();
}
public static Singleton_4 getInstance() {
return SingletonHolder.instance;
}
}