可以说单例模式是所有设计模式中最简单的一种。
单例模式就是说系统中对于某类的只能有一个对象,不可能出来第二个
单例模式也是23种设计模式中在面试时少数几个会要求写代码的模式之一。主要考察的是多线程下面单例模式的线程安全性问题。
1.多线程安全单例模式实例一(不使用同步锁)。不是懒加载的方式
public class Singleton{
private static Singleton singleton = new Singleton();//直接初始化一个实例对象
private Singleton(){
//private 类型的构造函数,保证其他类对象不能直接new一个该对象的实例
}
public static Singleton getSingleton(){ //该类唯一的一个public方法
return singleton;
}
}
上述代码中的一个缺点是该类加载的时候就会直接new一个静态对象出来,当系统中这样的类较多时,会使得启动速度变慢。现在流行的设计都是讲“延迟加载”,我们可以在第一次使用的时候才初始化第一个该类对象。所以这种适合在小系统。
2.多线程安全单例模式实例二(使用同步方法)
public class Singleton{
private static Singleton instance;
private Singleton(){
}
public static synchronized Singleton getInstance(){
//对获取实例的方法进行同步
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
上述代码中的一次锁住了一个方法,这个粒度有点大,改进就是只锁住其中的new语句就OK。就是所谓的“双重锁”机制。
3.多线程安全单例模式实例三(使用双重同步锁)
public class Singleton{
private static Singleton instance;
private Singleton(){
}
public static synchronized Singleton getInstance(){
//对获取实例的方法进行同步
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
方法二锁定整个方法块,方法三只是锁定了方法中的一个代码段。只是锁的“粒度”不同
4.使用内部类的单例模式
public class Singleton{
private Singleton(){
}
private static class Inner{
private static Singleton s = new Singleton();
}
private static Singleton getSingle(){
return inner.s;
}
public static void main(String[] args){
Thread ths = new Thread[200];
for(int i = 0; i < ths.length; i++){
ths[i] = new Thread(() -> {
Singleton.getSingle();
});
}
}
}
既不用加锁,也能实现懒加载。