一、单例模式
- 单例模式是一种创建型的设计模式,构造函数是私有的,因此只能在类中创建一个实例,且对外提供一个静态公有方法获取这个实例。
二、创建方法
1. 懒汉式(线程不安全)
java
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){ //多线程时,此处会产生线程安全问题
instance = new Singleton();
}
return instance;
}
}
2. 懒汉式(线程安全)
java
public class Singleton{
private static Singleton instance;
private Singleton(){}
public synchronized static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
3. 双重检查锁(DCL,Double-Checked Locking)(线程安全)
java
public class Singleton{
private volatile static Singleton instance;
private Singleton(){};
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
}
4. 饿汉式(线程安全)
java
public class Singleton{
private final static Singleton instance=new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
5. 静态内部类(线程安全)
java
public class Singleton{
private Singleton(){}
private static class InnerClass{
private final static Singleton INSTANCE=new Singleton();
}
public static Singleton getInstance(){
return InnerClass.INSTANCE;
}
}
6. 枚举类(线程安全)
java
public enum Singleton{
INSTANCE;
public void doSomething(String str){
System.out.println(str);
}
}