像@Dima Rostopira說,你可以實現一個Singleton,它在應用程序的過程中一次存在。
例與「位置」對象:一個活動的內部
final class LocationModel {
private Context mContext;
/** List of locations */
private ArrayList<Location> mLocations;
/** Static instance of LocationModel, accessible throughout the scope of the applicaton */
private static final LocationModel sLocationModel = new LocationModel();
private LocationModel() {}
/**
* Returns static instance of LocationModel
*/
public static LocationModel getLocationModel() {
return sLocationModel;
}
/**
* Sets context, allowed once during application
*/
public void setContext(Context context) {
if (mContext != null) {
throw new IllegalStateException("context has already been set");
}
mContext = context.getApplicationContext();
}
/**
* Asynchronously loads locations using callback. "forceReload" parameter can be
* set to true to force querying Firebase, even if data is already loaded.
*/
public void getLocations(OnLocationsLoadedCallback callback, boolean forceReload) {
if (mLocations != null && !forceReload) {
callback.onLocationsLoaded(mLocations);
}
// make a call to "callback.onLocationsLoaded()" with Locations when query is completed
}
/**
* Callback allowing callers to listen for load completion
*/
interface OnLocationsLoadedCallback {
void onLocationsLoaded(ArrayList<Locations> locations);
}
}
用法:
MainActivity implements OnLocationsLoadedCallback {
...
public void onCreate(Bundle savedInstanceState) {
...
LocationModel.getLocationModel().getLocations(this);
...
}
@Override
public void onLocationsLoaded(ArrayList<Locations> location) {
// Use loaded locations as needed
}
您可以簡單地使用Singleton模式, –