为了减少创建单例类的重复代码,首先,我们创建一个抽象类:

public abstract class Singleton<T> {
  private T mInstance;

  public Singleton() {
  }

  public final T get() {
    synchronized(this) {
      if (this.mInstance == null) {
        this.mInstance = this.create();
      }

      return this.mInstance;
    }
  }

  protected abstract T create();
}

然后,需要实现成单例的类中:

private static Singleton<StateManager> singleton = new Singleton<StateManager>() {
    @Override
    protected StateManager create() {
      return new StateManager();
    }
  };

  public static StateManager getInstance() {
    return singleton.get();
  }
评论

退出登录