概念
单例模式是提供一种创建对象的方式,这种模式确保只有一个对象被创建,并且为所有对象提供一个它的全局访问。
确保某个类只能创建一个对象,并且获取该类实例的方法是静态的
主要解决:
1、频繁创建实例、销毁实例
2、控制创建实例个数或者实例复用
特点
1、只有一个实例
2、必须自己创建自己唯一的实例
3、必须给所有对象提供访问这个实例的方法(静态的),防止子类重写篡改,通过(类名.静态方法名)访问
4、构造函数私有
实现方式
饿汉式(静态常量):
public class Singleton {
private Singleton()
{
}
private final static Singleton instance = new Singleton();
public static Singleton getInstanc()
{
return instance;
}
}
优点:在类装载的时候就完成了实例化,静态和final修饰的变量在准备的时候就已经加载到类里了,避免了线程同步问题,解决了线程不安全问题(线程不安全是指在多线程环境下,线程操作共享数据时,可能会引发数据错误)
缺点:没有lazyloading,在类加载就实例化,如果后续不需要访问该实例对象,就会占用内存,浪费资源
饿汉模式(静态代码块)
public class Singleton {
private Singleton(){}
private final static Singleton instance;
static{
instance = new Singleton();
}
public static Singleton getInstance()
{
return instance;
}
}
也是通过类加载机制实现的,优缺点同上面一样
懒汉式(线程不安全)
class Singleton{
private Singleton(){}
private static Singleton instance;
public static Singleton getInstance()
{
if(instance==null)
instance = new Singleton();
return instance;
}
}
实际开发中不能使用这种模式,只能在单线程中使用,多线程则容易造成线程不安全
懒汉式(线程安全,同步方法)
class Singleton{
private Singleton(){}
private static Singleton instance;
public static sychronized Singleton getInstance()
{
if(instance==null)
instance = new Singleton();
return instance;
}
}
优点:解决了线程不安全问题
缺点:效率低,该类实例只用创建一次即可,需要访问的时候直接return就可以。但是这样每个线程想要获得类的实例时候,都要进行线程同步。
懒汉式(同步代码块)
class Singleton{
private Singleton(){}
private static Singleton instance;
public static Singleton getInstance()
{
if(instance==null)
synchronized(Singleton.class){instance = new Singleton();}
return instance;
}
}
不能保证线程同步,因为如果a线程进入了if判断处停止,还未来的及往下执行,b线程通过了这个判断,创建了一个实例,这时候就容易创建多个实例
双重检查
private Singleton(){}
private static Singleton instance;
public static Singleton getInstance()
{
if(instance==null)
{
synchronized (Singleton.class)
{
if(instance == null)
instance = new Singleton();
}
}
return instance ;
}
解决了线程不安全的问题,也达到了延迟加载,效率较高,实例开发中使用这种模式
静态内部类
private Singleton(){}
private static class Singletoninstance
{
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance()
{
return Singletoninstance.instance;
}
静态内部类方式类加载时不会立即实例化,而是在需要实例化时,调用getInstance方法,才会装载,从而完成Singleton实例化
因为静态属性只会在第一次加载类的时候初始化,别的线程是无法进入的
优点:避免了线程不安全,实现延迟加载,效率高
枚举
public class Test {
public static void main(String[] args) {
Singleton singleton = Singleton.INSTANCE;
Singleton singleton1 = Singleton.INSTANCE;
System.out.println(singleton.hashCode());
System.out.println(singleton1.hashCode());
singleton.say();
}
}
enum Singleton{
INSTANCE;
public void say(){
System.out.println("hello");
}
}
保证线程安全,同时也防止反序列化时重建