单例模式详解(缺枚举)
ps:第一次写博客,以后会更新自己了解的和工作中遇到的问题和学的新知识,每天积累一些,进步一点。加油!明天会更好,真好!2018.9.19
首先,什么是单例模式呢?其实,所谓单例呢,就是说将类实例化且只实例化一次,这样做的话,在以后的编程中的逻辑处理时,再次用到此单例模式实例化出的对象时,就都是对同一个对象进行操作了!
单例模式比较常见的有以下几种:
1.饿汉模式
2.懒汉模式
3.双重锁懒汉模式
4.静态内部类模式
1.饿汉模式
所谓饿汉模式,就是在程序刚开始的时候就将对象创建好了,等待别人调用。(就好像一个饿汉着急吃饭一样,十分迫切)
缺点:在没有使用到该对象的时候,该对象就被创建好了,浪费资源
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {};
public static Singleton getNewInstance() {
return singleton;
}
}
2.懒汉模式
懒汉模式,只有当getNewInstance( )方法被调用的时候,才创建对象。(就好像一个懒汉一样,十分懒惰)
缺点:在单线程访问该单例模式时,不会发生什么问题,但是在多线程同时访问该单例模式时,就可能会发生,重复创建对象的问题
public class Singleton {
private static Singleton singleton = null;
private Singleton() {};
public static Singleton getNewInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
3.双重锁懒汉模式
为了解决懒汉的不安全问题,我们引入了锁的概念,当第一个线程进到加锁的区域之后,该锁会阻塞其他的线程进入,直到该线程完成任务,该锁释放。
缺点:加入锁之后,线程安全了,但是随之带来的是由于线程阻塞而导致的时间的增加;(在以后的学习中,你会发现,要么用时间换安全性,要么用安全性换时间,所有事情都不是十全十美的)
volatile关键字有两个作用(1)禁止了线程直接从cpu缓存中读取数据 而是读取最新从内存中取出的数据(2)禁止指令重排
public class Singleton {
private volatile static Singleton singleton = null;
private Singleton() {};
public static Singleton getNewInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
4.静态内部类模式
java虚拟机可以保证在一个类加载过程中,不受其他线程干扰,利用这一特性,可以实现单例模式
class Singleton{
private static class SingletonInner{
private static Singleton singleton = new Singleton();
}
public static Singleton getInstance(){
return SingletonInner.singleton;
}
}