Friday, 19 June 2015

Strategy Design Pattern

Strategy beneath Strategy Design Pattern ??

It defines a family of behaviors, encapsulate each of them, and clients can modify their behavioral implementations dynamically without interchanging the behavior in abstract client family.

How behavior is different from clients:

A simple example where one behavior eat is similar in all clients of Animal class. But an animal can choose from behavior of an herbivorous or carnivorous or an omnivorous diets. These behaviors could be modified dynamically.

Super Class Sub-Classes IDietBehavior Dietary Behavior
Animal Bird eat Herbivorous
Cow Carnivorous
Tiger Omnivorous
PolarBear

Please try yourself with above classes, after understanding the below bank example.

Client behaviors can also vary independently without worrying about internal implementations.
Why do we need this pattern ?
  1. Reduces long list of conditional behavior.
  2. Avoid redundant code.
  3. Independent clients and behavior to disallow other classes to force change the current behavior.
  4. Encapsulation to hide code from user.


AbstractBank.java
HsbcBank.java
AxisBank.java
ILoanProvider.java
BlockMortgage.java
Mortgage.java
Test.java

Drawbacks : Increased number of classes, managing the code is also a little difficult.

Sunday, 14 June 2015

Android Looper and Handler

Understanding Android Looper:

Looper keeps a thread specific event message loops. It's based on event driven programming paradigm; which waits for the events to process and when it has some event it immediately dispatches the specific event to the target(handler) to perform the desired action.

It is a default implementation of android framework and manages concurrency using message queue and declared as a final class to prohibit inheritance.

Looper's Message Queue:
  1. Synchronized Message Queue will process Messages and Runnables to the target placed on the queue by different threads. 
  2. Only one looper per thread is allowed and throws Illegal state exception("Only one Looper may be created per thread") if someone tries to prepare more than one looper in the same thread, this is enforced in Looper.java class.
  3. Looper Message Queue is managed by Handler, it add remove messages/runnables to message queue.
Threads by default doesn't have a message queue attached to communicate with them.

Looper key methods : 

prepare(): static method which initializes message queue and current thread object and holds a thread local constructor. Incumbent to call this method prior to running event loop.

loop(): runs the event message loop.
  1. Wait for messages in the queue. (Might block)
  2. Inversion of control: Dispatches messages to the respective targets(Handler). 
  3. Recycle messages once its processing done.

quit(): shut down the message event loop
  1. set message queue to quit and send null message while Quitting.
  2. null message stops event loop to stop.

Handler : The Brain, Master-Mind

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

When you create a new Handler, it is bound to the message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

Creating Handlers :
1. Need a looper to associate to a thread message queue.
2. Callback interface to handle messages when done processing by looper.
3. In default constructor, it uses current thread looper and if it's not prepared, will throw a run-time exception.

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()


Why do we need handlers ??
  1.  to schedule messages and runnables to be executed as some point in the future.
  2. to enqueue an action to be performed on a different thread from another thread. (Inter-thread communication).
Threads can communicate with each other using handler which can send messages and runnables to different threads looper.


Scheduling messages is accomplished with the post, postAtTime(Runnable, long), postDelayed, sendEmptyMessage, sendMessage, sendMessageAtTime, and sendMessageDelayed methods.



UI threads has its own looper prepared from ActivityMainThread.java to receive messages from itself and other threads. UI thread message queue is accessible to all  threads using method Looper.getMainLooper(), AsyncTask, CursorLoader, AsyncQueryHandler, services and other app components all are using main thread looper to deliver messages to the main thread.