什么是单例模式
在我们想表示某个东西只能存在一个的时候,就会有只能创建一个实例的需求。实现这个确保只能生成一个实例需求的模式,就叫单例模式。
单例模式分类
单例模式分为饿汉式和懒汉式,饿汉式在加载时就会创建实例,而懒汉式则在第一次引用时才会被实例化。下面看一下两种实现方式的代码。
1、饿汉式
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton(){
System.out.println("生成了一个实例。");
}
public static Singleton getInstance(){
return singleton;
}
}
2、懒汉式
public class Singleton {
private static Singleton singleton = null;
private Singleton(){
System.out.println("生成了一个实例。");
}
public static Singleton getInstance(){
if(singleton==null){
singleton = new Signleton();
}
return singleton;
}
}
1)线程不安全懒汉式
在懒汉式中,只有调用了getInstance时,才会创建一个Singleton实创赋值给singleton引用。但是大家可以看到,在懒汉式中其实是线程不安全的。如果采用多线程去调用getInstance,会存在同时判断if中的内容为true,然后会导致在前一个判断后创建的实例会被后判断的创建给覆盖。想要实验的同学可以使用已经降低了处理速度的懒汉式。
public class Singleton {
private static Singleton singleton = null;
private Singleton(){
System.out.println("生成了一个实例。");
slowdown();
}
public static Singleton getInstance(){
if(singleton==null){
singleton = new Signleton();
}
return singleton;
}
private void slowdown(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
}
}
2)线程安全懒汉式
如果想要使懒汉式较为严谨,需要使用到synchronized来创建互斥锁,下面为线程安全的懒汉式单例模式实现代码。
public class Singleton {
private static Singleton singleton = null;
private Singleton(){
System.out.println("生成了一个实例。");
slowdown();
}
public static synchronized Singleton getInstance(){
if(singleton==null){
singleton = new Signleton();
}
return singleton;
}
private void slowdown(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
}
}