package com.hc.viewmodel;

import android.app.Application;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.support.annotation.NonNull;

/**
 * @author jewel
 */
public class ViewModelInstance extends ViewModelProvider.NewInstanceFactory {

    private static volatile ViewModelInstance INSTANCE;

    private Application application;

    public static ViewModelInstance getInstance(Application application) {
        if (INSTANCE == null) {
            synchronized (ViewModelInstance.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ViewModelInstance(application);
                }
            }
        }
        return INSTANCE;
    }

    private ViewModelInstance(Application application) {
        this.application = application;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(UserViewModel.class)) {
            return (T) new UserViewModel(application);
        } else if (modelClass.isAssignableFrom(FJYDViewModel.class)) {
            return (T) new FJYDViewModel(application);
        }
        return super.create(modelClass);
    }
}
