banner



Command Design Pattern To Mobile App

Mobile Application Design Patterns — Command Processor

Weezlabs

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."

Martin Golding

Quick story: during the development of one my projects, I faced several challenges relating to the use of the Google Places API, networking communication between the application and the server. My intuition and spaghetti-code with AsyncTasks told me there should be a better way to organize these interactions, so I found the Command Processor design pattern. Let's observe how it can be implemented in Android apps.

Let me exp l ain some of the challenges I faced. The application is intended to show previews of places chosen by the user. After one clicks on previews, it should show all associated images of the chosen place by ID. My first thought was to use AsyncTask, but I shortly discovered a better method. A lot of background operations required multiple AsyncTask calls, so it was extremely inefficient. Instead I found the Command Processor design pattern which is more suitable for this app.

The Command Processor design pattern separates the request for a service from its execution. The main feature of this design pattern manages requests as separate objects and planning their execution. It also provides additional services such as keeping requests or creating queries for requests. The below diagram shows the relationship between components of design pattern:

Application area:

  • Programs with reach UI where users interact with systems by using graphical tools, such as text editors and image editors. Commands (the same as requests) are used for executing tasks after clicks or hotkeys. Commands are the objects which are transferred to the Command Processor for execution.
  • Distributed or parallel systems. Using this design pattern allows one to send commands for execution in a different thread. It's also possible to create thread queues.
  • Apps use network communications.

How can this design pattern can be applied for developing Android apps? There are a lot of ways to create these design patterns (IntentService or HaMeR –framework (HaMeR stands for Handler, Messages, Runnable)) I chose to use the HaMeR — framework, so the test project shows tracks and a list of places. There are two types of requests(commands):TracksRequest and PlacesRequest respectively. Both classes are child of abstract CommonRequest for Command Processor.

          public abstract class CommonRequest { public abstract void sendRequest(int i); public abstract List<Result> parseRequest(); }        

Image.1 Base class CommonRequest for requests

          public class PlacesRequest extends CommonRequest { private int id_; public PlacesRequest(int id) { id_ = id; } public int getDataRequest() { return this.id_; } public List<Result> parseRequest() { // Let's imagine we have parsed json List<Result> results = new ArrayList<>(); Result fakePlace = new Place("Place", "description"); results.add(fakePlace); return results; } }        

Image.2 PlaceRequest

          public class TracksRequest extends CommonRequest { private int id_; public int getDataRequest() { return this.id_; } public List<Result> parseRequest() { // Let's imagine we have parsed json List<Result> results = new ArrayList<>(); Result fakeTrack = new Track("Track", "description"); results.add(fakeTrack); return results; } }        

Image.3 TracksRequest

Method execute() does all the work: creating the URL for the API, creating a new Thread, parses json and sends the result to the controller by means of the Handler.

          public void execute(final MessageController controller, final CommonRequest request) { Thread background = new Thread(new Runnable() { @Override public void run() { try { request.getDataRequest(); Thread.sleep(5000); List<Result> results = SimulateHttpRequest(request); controller.sendMessage(controller.obtainMessage(States.REQUEST_COMPLETED, results)); } catch (Exception e) { } } }); background.start(); }        

Image.4 sendAsyncPlaceRequest()

The next step is the implementation of the Command Processor for managing and execution requests.

          public class RequestProcessor { private UpdateCallbackListener clientActivity_; public RequestProcessor(UpdateCallbackListener clienActivity) { this.clientActivity_ = clienActivity; } public void execute(final MessageController controller, final CommonRequest request) { … } public void updateActivity(List<? extends Result> results) { clientActivity_.onUpdate(results); } private List<Result> SimulateHttpRequest(CommonRequest request) { List<Result> results = request.parseRequest(); return results; } }        

Image.5 Realization RequestProcessor

Now we need to implement a controller, which will send different commands depending on states. The result will be sent from thread by means of the Handler.

          public class MessageController extends Handler { private static MessageController instance = null; private RequestProcessor processor_; public void init (UpdateCallbackListener listener) { processor_ = new RequestProcessor(listener); } public static MessageController getInstance(){ if (instance == null){ instance = new MessageController(); } return instance; } public void handleMessage(Message msg) { switch (msg.what) { case States.INIT_REQUEST: CommonRequest request = (CommonRequest)msg.obj; processor_.execute(this,request); break; case States.REQUEST_COMPLETED: List<Result> results = (List<Result>)msg.obj; processor_.updateActivity(results); break; default: break; } } }        

Image.6 MessageController

For updating UI we have to implement onUpdate() in main activity:

          public interface UpdateCallbackListener { void onUpdate(List<? extends Result> results); }        

Image.7 UpdateCallbackListener()

          public void onUpdate(List<? extends Result> results){ tracks_ = (List<Track>) results; TrackAdapter trackAdapter = new TrackAdapter(this,tracks_); listView_.setAdapter(trackAdapter); }        

Image.8

The next diagram shows the dynamic of this design pattern:

In summary, these steps need to be implemented in order to use this design pattern:

  1. Define the interface for abstract commands.
  2. Define the way to allow returns the result of commands. In our example we defined interface UpdateCallbackListene with onUpdate() method for each activity.
  3. Implement each command. We defined two types of commands — TracksRequest and PlacesRequest.
  4. Implement the controller for sending commands.
  5. Implement the Command Processor class for execution of commands

Pros and Cons of this Design Pattern

Pros:

  • In apps such as text editor, different items of UI interface can use the same commands. For example, the "Create" button in the main menu and the "Create" button in the popup menu, they both use the same command.
  • Possibility to send async requests, schedule requests.
  • Flexibility with adding new features.

Cons:

  • It is necessary to keep track of each condition and process it respectively
  • The number of commands can be enormous
  • Two-way communication. When activities trigger requests, it is necessary to send result back and update UI.

Conclusion

If you're a developer, then you've used these design patterns in your projects. However, as an architect of mobile applications, this can be a very broad and interesting topic. In addition, I would like to say that libraries such as EventBus or RxJava would make the implementation of this pattern easier. The main goal of this article was to demonstrate Command Processor design pattern without any additional features for simplicity. Of course, it's ultimately up to you what kind of tools to use — see you later and happy coding!

Sources:

[1]PATTERN-ORIENTED SOFTWARE ARCHITECTURE VOLUME 1. Douglas Schmidt, Michael Stal, Hans Rohnert, Frank Buschmann

[2] Command Revisited https://www.dre.vanderbilt.edu/~schmidt/PDF/CommandRevisited.pdf

[3] Project https://github.com/GregaryMaster/CommandProcessor

Command Design Pattern To Mobile App

Source: https://medium.com/@weezlabsteam/mobile-application-design-patterns-command-processor-2ea3e0fad43c

Posted by: williamshisenturning.blogspot.com

0 Response to "Command Design Pattern To Mobile App"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel