对APP单例的统一封装(常规式)

1,214 阅读3分钟

单例模式(Singleton)是一种使用率非常高的设计模式,其主要目的在于保证某一类在运行期间仅被创建一个实例,并为该实例提供了一个全局访问方法,通常命名为getInstance()方法。在APP开发中,我们会遇到大量的单例,如各种ImageManager、ShareManager、DownloadManger、ApiService等,此外单例的不恰当使用还会带来内存泄露问题,因此,对单例进行统一封装、管理就显得很有必要了。

先从单例模式说起

单例模式的实现主要有以下几种方式:饿汉式、懒汉式、静态内部类、enum等,在实操过程中,我们经常采用线程安全下的懒汉式和静态内部类式实现,我们简单回顾以下这两种方式:

懒汉式

所谓懒汉,就是lazy load,主要解决的问题是避免单例在classLoader的时候就被预先创建,而是在使用的时候再去创建,同时,这这个模式下听过线程锁机制来保证线程安全,它的实现如下:

public class Singleton {

    private static volatile Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}

静态内部类式

这种方式是通过Java类加载机制来保证线程安全,JVM Class Loader时会执行类的静态变量赋初始值和执行静态代码块中的内容,ClassLoader肯定是单线程的,保证了单例的唯一性。而静态内部类只有在调用了getIntance方法时,才会触发内部类的装载,因此这又保证了延迟加载。具体的实现如下:

public class Singleton {
	
	private static class Instance {
		private static Singleton instance = new Singleton();
	}

	private Singleton() {

	}

	public static Singleton getInstance() {
        return Instance.instance;
    }
}

再谈单例的封装

我们要解决的问题有两个:

  1. 方便的单例创建;
  2. 避免内存泄露,尤其是APP开发过程中的 context 造成的泄露问题

具体实现

DJContext

DJContext 持有 ApplicationContext, 避免因为 context 带来的内存泄露问题;DJContext 提供统一的单例获取方式,比如: UserManager um = DJContext.getService(UserManager.class);

public final class DJContext {

    private static Context mContext;

    public static void init(Context context) {
        mContext = context.getApplicationContext();
    }

    public static <T> T getService(Class<T> tClass) {
        checkContextValid();
        return ServiceRegistry.getService(mContext, tClass);
    }

    private static void checkContextValid() {
        if (mContext == null) {
            throw new IllegalStateException("must call method [init] first !!!");
        }
    }
}

ServiceRegistry

采用静态注册的方式,注册不同单例的获取方式,同时通过内部抽象类实现延迟加载。

final class ServiceRegistry {

    private static final Map<String, ServiceFetcher> SERVICE_FETCHERS = new HashMap<>();

    private static <T> void registerService(String name, ServiceFetcher<T> fetcher) {
        SERVICE_FETCHERS.put(name, fetcher);
    }

    static {
        registerService(UserManager.class.getName(), new ServiceFetcher<UserManager>() {
            @Override
            public UserManager createService(Context context) {
                return new UserManager();
            }
        });

        registerService(ImageManager.class.getName(), new ServiceFetcher<ImageManager>() {
            @Override
            public ImageManager createService(Context context) {
                return new ImageManager(context);
            }
        });
    }

    public static <T> T getService(Context context, Class<T> tClass) {
        final ServiceFetcher fetcher = SERVICE_FETCHERS.get(tClass.getName());
        return fetcher != null ? (T) fetcher.getService(context) : null;
    }

    private static abstract class ServiceFetcher<T> {
        private T mService;

        public final T getService(Context context) {
            synchronized (ServiceFetcher.this) {
                if (mService == null) {
                    mService = createService(context);
                }
                return mService;
            }
        }

        public abstract T createService(Context context);
    }
}

使用方式

使用分两步:

1、DJContext的初始化:一般放在 Application.onCreate() 中;

@Override
public void onCreate() {
    super.onCreate();
    DJContext.init(this);
}

2、通过DJContext获取实例;

比如有个实例叫做:

public class ImageManager {

    private Context context;

    public ImageManager(Context context) {
        this.context = context;
    }
}

在ServiceRegistry预先进行register;
然后使用时通过以下方式:

ImageManager imgManager = DJContext.getService(ImageManager.class);

缺点 因为要实现单例可以被 register,所以单例类的构造方式只能是 public/ protected 的,这与单例的构造方法需是 private 有所出入。针对这一点,使用过程中可以通过将所有的单例放到一个 package 下,然后采用 protected 形式的构造方法.

这里我把这种封装称之为常规式,显然还有一种非常规式,非常规式可以基于动态代理来实现封装。敬请期待...