I am looking for some design patterns to use controlling a set of Activitys in an Android application. I am currently developing an app which I feel will go under many many revisions of the UI until its "final" release (if there ever is one). I was thinking something along the lines of an Observer pattern using a controller in the Service but I can't find any good examples. The only thing I find common references to is using AIDL for inter-process interface binding, which will not be applicable.
Basically what I want is for the Activity to implement a defined Interface such as showLoginScreen(), loginError() etc. such that ANY UI should be able to implement (the controller is not tied directly to the view, only its interface). If this is the cleanest way to accomplish this, what is the best accepted way of getting handles to active Activitys? I have always been confused what happens when you invoke a method on an Activity that is not active.
I was thinking something along the lines of a Map in the Application class serving as a singleton? The put() / remove() of the Map would be tied to onStart() and onPause(). This still doesn't guarantee the Activity is still alive though...a reference could be gained with a get() on the key, and then it could be paused() before the Service has a chance to call its interface.
Any suggestions or insight would be appreciated.
edit: I have looked at other posts such as MVC pattern on Android however they mostly don't address implementation (and that accepted answer I just flat out disagree with anyways)
To use an observer/observable pattern between your activities and your service, you will need to use Bound services.
This way, you can get a handle to the IBinder which can act as your Observable and you do not have to worry about AIDL. You can ensure that the Service has been bound to in the onServiceConnected() method in your ServiceConnection. Keep in mind that your service will only be alive as long as there is an Activity bound to it, otherwise it will be stopped.
I would recommend reading the android Bound Services documentation as it explains the usage very well.
Related
Lately I've read this comment on Reddit:
I think EventBus on android is popular because people don't know how to share a java object reference between android components like a Fragment and an Activity, or 2 Activities and so on. So basically I think people don't know how 2 Activites can observe the same object for data changes which I think comes from the fact that we still don't know how to architect our apps properly.
As far as I know:
directly reference values
((HostActivity)getActivity()).someValue
may cause problem such as memory leaks or NullPointerException
Callbacks or other observer pattern
EventBus,inner class like listener and etc
So I was curious that whether there is any other ways , could you share with me on it?
imo, there are few ways out of your opinion such as:
use local db, now ORM like Realm is really popular, its also safe way.
use share preferences if your object is able to convert to json, its up to your situation.
use intent with serialize/parcelable object bundle.
use a singleton, now #scope with Dagger 2 is good choice.
use RxJava as event bus.
Within Java you can create an Observer-Observable set of classes in which the Observable can call the Observer. You can also in java explicitly reference an owning class instance in a child instance of another class and call the owning class instance's public functions.
Which is the better approach to take? Which is more beneficial in different scenarios, one example being Multi-Threading?
The Observer Pattern should be used whenever you don't know or don't care who is observing you. This is the key-concept in event-driven programming. You don't have any control of who is observing or what they do when you broadcast your events. Like you already mentioned in your comments, this is great for decoupling classes.
An example of a usage could be in a plugin-architecture:
You write a basic mail-server that broadcasts whenever a mail is received. You could then have a spam-plugin that validates the incoming mail, an auto-reply service that sends a reply, a forward service that redirects the mail and so on. Your plain mail server (the observable) doesn't know anything about spam, replies or forwarding. It just shouts out "Hey, a new mail is here" not knowing if anyone is listening. Then each of the plugins (the observers) does their own special thing, not knowing anything about each other. This system is very flexible and could easily be extended.
But the flexibility provided by the Observer Pattern is a two-edged sword. In the mail-server example, each plugin handles the incoming mail in total isolation from each other. This makes it impossible to setup rules like "don't reply or forward spam" because the observers doesn't know about each other - and even if they did, they wouldn't know in what order they are executed or has completed. So for the basic mail-server to solve this problem, It'll need to have references to the instances that does the spam/reply/forward actions.
So the Observer Pattern provides flexibility. You could easily add a new anti-virus plugin later, without having to modify your plain mail server code. The cost of this flexibility is loss of control of the flow of actions.
The reference approach gives you total control of the flow of actions. However you would need to modify your plain mail server code if you ever need to add support for an anti-virus plugin.
I hope this example gives you some ideas of the pros and cons of each approach.
In regards to multi-threading, one approach isn't favorable over the other.
I'm noticing some strange behavior in my app that smells like a lack of thread-safety. I'm working on reproducing it, but in the meantime I wanted to ensure I'm making the right assumptions about how the class that contains my endpoint handlers is used from a threading perspective. Most of what happens is opaque to me, because I'm not the one instantiating the class in the first place. To state the obvious, it must be some black magic in Endpoints.
MY ASSUMPTION
An instance of the class that holds my endpoint handlers is created for every single request that comes into my app. Based upon that assumption, it's ok for that class to have non-thread-safe objects that get used by my handlers.
MY FEAR
The instances of Endpoint handler classes are reused across requests.
So, which is it? Regardless of the answer, I think it would make sense for me to remove the ambiguity in my app and assume the worst, because I don't think I have any control over how Endpoints behaves. In my case, I'm creating a JDO/DataNucleus PersistenceManager (not thread-safe) when constructing the class housing my endpoint handlers. I should probably just create it in each handler as a local, or use a ThreadLocal.
I can probably also fashion a test to prove one or the other. I'll post back an answer to my own question if I do.
Proxy - what code (and where) translates ProxyService into RealService calls? Why/when use this?
Layers - how to implement?
Memento - why not just persist state to a cache or file?
My understanding of the Proxy pattern is that you have some kind of Service interface that has ProxyService and RealService concretions. For some reason, you can't access the RealService, so you code against a ProxyService instance and then let the framework link the proxy to the real instance of your service. Only two problems:
I can't think of a single example when I would have access to Service and ProxyService, but not RealService - can someone provide examples as to when this could happen?
How is this different from the Memento pattern? My understanding of Memento's definition is that it is used for saving an object state, which is what a Proxy is really doing, yes? If not please explain how Memento is different than Proxy! Thanks in advance!
First off, I'll caveat my answer by saying that I don't believe there are any hard and fast rules about patterns - you take what you need from them and nothing more. The way that I use certain patterns is undoubtedly different from how another developer might choose to use them. That said, here's my take on your question.
Proxy Pattern Explained
The way I know the Proxy design pattern, you use it to do two things:
Restrict access to otherwise public methods of a particular object instance
Prevent otherwise-expensive, and unnecessary instantiation costs, by instantiating the concrete object on the first call to the proxy, then passing all further calls on the proxy through to the concrete instance your proxy created.
Maybe RealService has a method doSomethingReallyDangerous() that you want to hide. Or even more innocuous, maybe RealService has several hundred methods that you don't need to see every time you type the . after a RealService instance's variable name. You'd use a proxy for any of this.
For further reading, this article has a lot of good information:
http://sourcemaking.com/design_patterns/proxy
Differences with Memento Pattern
The Memento pattern allows you to roll back an object to its original state, or some previous state, by storing intermediate states alongside the concrete object. Sort of like an "undo" for programming. You'd probably use a Proxy pattern to implement Memento, but Proxy doesn't guarantee saving of object state or rollback - it just lets you refer to the same object for method calls if instantiating that object over again is prohibitively expensive.
So hopefully that helps - I like to think of Memento as a more full-featured version of Proxy, but not all Proxy implementations are Mementos.
Proxy is when someone is expecting a certain object, and you lie to him, and you say: Yes, here you have your object, but you are actually giving him something else...
Common uses for proxy:
To implement Lazy initialization: You are asked for an object representing the contents of a big file, or something which is very expensive to acquire, and you know that it's not needed at this right moment, or it might in fact never be used really. So you pass a proxy, that will only acquire the resource when it's 100% completely necessary (You can also start acquiring the resource anachronistically, and make the process using the proxy only start waiting when it really needs it). This is pretty common in ORMs. Also futures and promises implement something like this
To intercept calls:
You can pass a proxy which actually knows the real object, and intercept the calls that it gets, and do something interesting like logging them, changing some of them, etc...
There are also a lot of advanced and complex usages of the proxy, given that you often have the ability to determine the behavior at runtime. sorry for going out of Java, but in C#, Castle Proxy is used to implement mock objects for testing. You can also implement with a proxy things like chaining in underscore. And you can simulate a lot of "dynamic languages" features in static languages using proxies. You can also evaluate a piece of code with a proxy that actually logs every call that is made, and returns new proxies every time, to reconstruct the "original source code" by just executing it.
Memento pattern: is another thing completely. You use it when you want to work with an object, save it current state, counting doing thins with that object, and after a while you might want to choose to rollback to the previous state. You can use it to implement transactional behavior in your objects, when undoing the things by code is difficult. You can implement undo & redo functionality with this. (Instead of saving the change-delta, you save the full state). You can use it in simulations to start every time from the same point (You could say that a Source Version Server uses memento every once in a while [they generally use a combination of memento + delta changes]). A snapshot of a virtual machine or an hibernate of a computer is also a use of the memento pattern. And saving the state of something, so you can reproduce the exact same situation is also memento.
So for my current project, there are basically three main Java classes:
GUI
Instant Messaging
Computation
Essentially, there needs to be full communication, so we've decided to use the mediator approach rather than than allow the GUI to run the entire project.
Basically, the mediator is going to encapsulate the communication. The problem we've run into is how to allow the GUI components to update without building a ton of methods for the mediator to call anytime something completes.
Ex. Say the GUI wants to log in the user, it goes through the mediator to create a thread and log in, but then the mediator has to relay the success/failure back to GUI as well as update a status message.
The other issue is things that need to update the GUI but do not need the moderator. Is it practical to just allow the GUI to create an instance of that class and run it or should everything go through the mediator?
Our original design just had the GUI managing everything, but it really killed reusability. Is there a better design method to use in this case?
If you're finding Observer to bring too much overhead, Mediator may be the best way to go. I definitely think that you shouldn't have the GUI run the show. If you're going to use the Mediator pattern, the mediator itself should be in charge. Something you might consider is a variant of the Command pattern. If you were using Ruby, I might recommend passing function callbacks around as a means of avoiding having the mediator contact the GUI for every little thing. But since it's Java, some form of encapsulating an action in Command pattern style may help.
If you don't want the callback/notification to be triggerd by the mediator, you can inject the callback into the login function and have login call it when it finishes.
I don't know how you would go about injecting the callback in Java, though. In a language where functions are first class citizens, you could just pass the function, but you're in Java so I guess you will have to use the command pattern as kmorris suggested.
You might also try having the GUI give the mediator a callback object that handles retrieving return values or setting whatever values you need (a version of the Command pattern). There would then be one per call from the GUI to the mediator.
Another thought is to group the methods the mediator calls into semantically related chunks. In particular if the mediator has sections where it tends to call several GUI methods in a row:
gui.a()
gui.b()
gui.c()
you can create a single method that handles the result of calling all three. The advantage of semantically grouped methods (i.e. setFileInformation over setFileMenu, setTab, etc.) is also then if you need to change the GUI, the contents of the methods might change, but the call the mediator makes may not.