Question

I am fairly new to android and after reading a book and taking alot of tutorials i am about to create my first "real" app.

My question is rather simple does: Is the mediator design pattern still a good choice when designing android apps?

If yes is there any design patterns you should avoid when programming android apps?

if no is there any substitude to the mediator pattern you could use to have a collection of your instances of the different objects?

Était-ce utile?

La solution

I suggest creating a model class (let's call it MyModel) and creating object of this class in Application.onCreate (not Activity.onCreate).

After that adding getter for that, so you can get this model from any Activity or Service like this:

MyApplication app = (MyApplication) getApplication();
MyModel model = app.getMyModel();
User user = model.getCurrentUser();

etc.

Also creating BaseActivity class can save you typing if you create method there protected MyModel getModel() which returns model from the first 2 lines of the code above.

Edit:

You need to create a class that extends Application and register this class in AndroidManifest.xml.

This is how: https://stackoverflow.com/a/2929927/2183804

Edit (about singleton):

It is said to be an anti-pattern (not only on Android). In Android I have seen people ending with singleton with accessor like MySingleton.getInstance(Context), because they needed Context anyway, e.g. for SharedPrefs or DB access. This is what Application is for, so there is no need to create additional, hackish entity, which could be used in a wrong way: MySingleton.getInstance(null) from a place where there is no Context available. This could lead to NPE after process is killed and restarted.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top