挺久没更新博客。趁着最近不太忙。打算写一下设计模式方面的一些知识。今天写的时平时工作中比较常用的设计模式-----单例模式。
定义:保证一个类仅有一个实例,并提供一个访问它的一个全局访问点。平时我们工作中比如需要经常的调用一个实例做某件事情时,并且这个实例只能有一个的时候,会用到这个模式。比如图片加载器,持久化存储等等情况下使用。
单例模式有多种写法,每种有利有弊。需要我们自己权衡利弊去使用。
第一种:饿汉模式。我们先看下代码:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
这种方式在类加载的时候就已经初始化了一个实例,所以加载类的速度慢,但是获取实例对象的速度快。这种写法的话,如果我们整个项目自始至终没用到这个实例,则会造成内存的浪费。
第二种:懒汉模式。代码:
public class Singleton {
private static Singleton instance ;
private Singleton(){
}
public static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
这种写法的话在我们第一次调用getInstance()方法时才会初始化,虽然节约了内存,但速度会慢,而且在多线程时会线程不安全,不能正常工作。
第三种:懒汉模式(线程安全)
public class Singleton {
private static Singleton instance ;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
我们加上同步锁之后在多线程中可以正常工作,但是这种方法我们在每次调用实例的时候都会加上同步锁,这样会造成不必要的资源开销,而且工作中大部分用不到同步。
第四种:静态内部类单例模式
public class Singleton {
private static Singleton instance ;
private Singleton(){
}
public static synchronized Singleton getInstance(){
return SingletonHolder.sIntance;
}
private static class SingletonHolder{
private static final Singleton sIntance = new Singleton();
}
}
第一次加载Singleton时不会初始化sIntance,在第一次调用getInstance方法时才会初始化sIntance,这样可以确保线程安全,也能保证Singleton的唯一性,平时推荐使用这样方法。
还有一种枚举单例,但是代码比较简单,平时应用很少用到枚举单例,可读性也不是很高,今天就不介绍了。