Wednesday, October 5, 2011

My Android AsyncTask implementation vis-a-vis Command Pattern...

Note: If someone wants to learn about the Asynctask internal, please have a look at this document.

As i was developing a sample Android App to showcase the Android AsyncTask, i found it very much similar to the Command design pattern. i would like to share this with you...


Let me first state about the Command design pattern. The purpose of the command pattern is to associate a command object with its receiver where the receiver knows what to do when this command is called... We have an interface called command, from where we deduce different concrete commend classes... The client creates the concrete command objects passing the information of the receiver for that command... And when the invoker ( which is generally a framework object) calls the execute method of the command, the concrete command actually executes it with the help of the Receiver’s functionalities...


The class diagram of the command pattern is as follows:

And the sequence diagram is as follows:




Now let me decipher my App to show how it implements the command pattern... the class diagram of this application looks like the following:



As it becomes clear from the code, the client (which is the Activity class) creates a concrete command class, the Callback interface through the concept of Anonymous inner class (see the code c = new CallBack() {.....}; it then stores this command in the invoker (the MyAsyncTask class) by passing the reference to the invoker (see the line of code aTask = new MyAsyncTask(c)).. . the invoker (the MyAsyncTask class here) stores a reference to this command object... then if something interesting happens, the invoker calls the functionality from the callback interface (the command)... the functionality of the callback interface have been implemented in the Client (the Activity class)...

hence i think that my implementation of the Asynctask is very similar to the Command design pattern implementation...

Hope this discussion helps the android learners...

Here is my AsyncTask implementation.. Here you can find the callback interface... And you can find the main Activity class here.

And here goes the apk of the sample app... You can clone the whole source from here...

No comments: