I've been adopting the MVP pattern to my Android Applications and have come across a stumbling block implementing something with the pattern, maybe my naivety, or lack of experience with programming so far and just some more skilled programmers ideas.
I have 2 Activities, lets say the View Layer, that each have their own Presenter
and Model
, each implementing their own interfaces that each the corresponding layer calls methods from (each layer with its own set of responsibilities). The View
initialises the Presenter
, passing in a this
reference, and the Presenter
then initialises the Model
passing in a this
reference, so everything is hooked up and can access each layer, nothing special here - something like:
ViewA <------> PresenterA <-------> ModelA
ViewB <------> PresenterB <-------> ModelB
This works fine, however I would like to communicate from the instance of ModelA
to the instance of ModelB
something like this http://ift.tt/1MI7eUT obviously through the appropriate Presenter first i.e.
ModelA -----> PresenterA ------> ModelB
For this work PresenterA
needs a reference to ModelB
. How can this be done as each are initialised separately? Each Activity has a reference to its Presenter and Presenter to Model for communication but thats it? Would a Dependency Injection
library such as Dagger be able to help here, I've seen the @Singleton
annotation but does this mean it creates only one instance, or one instance per class its 'injected' into (I'm only just started using these libraries). Could I use a static WeakHashMap<Integer, Presenter>
or static HashMap<Integer, WeakReference<Presenter>>
to store the references and get as required - could this lead to memory leaks being static? I have read some docs on WeakHashMap<>
and does seem plausible, however not sure if making it static would complicate things as Presenters have references to View (Activities) that can come and go (Presenters themselves have reference to the View
layer via WeakReferences<View>
objects).
As I say I maybe a bit naive, and getting myself twisted up a bit! Hopefully there is a novel simple solution, ideally without using any external libraries, which I'm guessing everything is possible without but they make life easier with in particular use cases.
An answer with a simple code implementation would be great.
Thanks
Aucun commentaire:
Enregistrer un commentaire