单例模式
采取一定的方法保证在整个软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。
1.饿汉式(静态常量)
//饿汉式(静态变量)
class Singleton{
//1.构造器私有化(防止new)
private Singleton(){
}
//2.本类内部创建对象实例
private final static Singleton instance = new Singleton();
//3.提供一个共有的静态方法,返回实例对象
public static Singleton getInstance(){
return instance;
}
}
优缺点
1)优点:在类装载时就完成了初始化,避免了线程同步问题。
2)缺点:没有达到lazy loading的效果,如果从始至终没有使用这个实例,会造成内存浪费。
2.饿汉式(静态代码块)
class Singleton{
//1.构造器私有化
private Singleton(){
}
//2.本类内部创建对象实例
private static Singleton instance;
//在静态代码块中创建代理对象
static {
instance = new Singleton();
}
//3.提供一个共有的静态方法,返回实例对象
public Singleton getInstance(){
return instance;
}
}
3.懒汉式(线程不安全)- 不推荐使用
class Singleton{
private static Singleton instance;
private Singleton(){
}
//提供一个静态的共有方法,当使用到该方法时,才去创建instance
//即懒汉式
public static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
优缺点
1)实现了lazy loading,但是只能在单线程下使用
2)如果在多线程下,如果一个线程进入了if判断,还未来得及往下执行,另一个线程也通过了这个判断语句,这时会产生多个实例
4.懒汉式(线程安全)- 不推荐使用
class Singleton{
private static Singleton instance;
private Singleton(){
}
//提供一个静态的共有方法,当使用到该方法时,才去创建instance
//即懒汉式
public static synchronized Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
5.双重检查-实际开发推荐
class Singleton{
private static volatile Singleton instance;
private Singleton(){
}
//提供一个静态的共有方法,加入双重检查代码,解决线程问题,同时解决懒加载问题
//即懒汉式
public static synchronized Singleton getInstance(){
if (instance == null){
synchronized (Singleton.class){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
优缺点:
1)双重检查在多线程常用,进行两次if判读,可以保证线程安全
2)实例化代码只用执行一次,后面再次访问时,判断if成立,直接return实例化对象
6.静态内部类
class Singleton{
private Singleton(){
}
//写一个静态内部类,该类中有一个静态属性 Singleton
private static class SingletonInstance{
private static final Singleton INSTANCE = new Singleton();
}
//提供一个静态共有方法,直接返回SingletonInstance.INSTANCE
public static synchronized Singleton getInstance(){
return SingletonInstance.INSTANCE;
}
}
7.枚举
推荐使用
总结
1)单例模式保证了系统内存中只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能
2)当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用new
3)使用场景:需要频繁进行创建销毁的对象、创建对象时耗时过多或耗费资源过多但又经常用到的对象