Tuesday, September 16, 2014

Command Pattern in Java

This is the story of Antony "The ruthless mafia boss". Antony is ruling city mafia for over 3 decades now. Every crime in the city happens with his orders.
He has 4 Gangs working under him. He takes care that the authorities, police etc. are under control. Now he is 65 years old but still he has not lost his control. Although he don't go into the details of each and every crime and its execution but his approval is must.
Every morning people assemble in his courtyard with their requests. They meet his son who looks into all the details and decide if the request will go further and to which gang. For such requests he creates a letter with all the required information and then they take this letter to Antony. This letter has all the details required for the execution of crime.
Antony never opens the envelope. If situation is favourable. Connections with Police and all other authorities are under control he just says "DO IT". Then the letters reaches the Gangs who execute the orders.

Nice story, but the title of this article is 'Command Pattern' and not 'Godfather Returns'. So, time to put on our Java glasses and read the story again. 
I told you this story as Antony has been using Command Pattern to run his mafia successfully since ages. 

The Gangs (Executors)

Although they don't seem to be very important in the story but they are the ones who execute everything and they know "How to do it?".
Here are the 3 Gangs which specialize in different types of crimes.

Here is sample Gang Class-

These Gangs only wait for commands(Letter) from Antony to do the work.
The Letter
Letter plays a very important role it is a command for the Gangs. And there could be different types of commands.

  • MurderCommand
  • KidnapCommand
  • StealCommand ....And More

How can a Letter reach the destination without address? 
So, Letter should have information about the Gang where it should go.

Command object should have the reference of the Executor Object (Gang object).
Which will do the real execution.

So,  MurderCommand has Gang3 object. It calls murder() method of Gang3 from its execute() method.
                                                              Command has Gang

In this case calling a single method murder() is enough for execution. 
But in some cases Command might need to call mutiple methods of one or more executors. 

Example- There could be a Macro command to steal, kidnap & murder.
So, execute() method will call steal(), kidnap() and murder() method of Gang1, Gang2 & Gang3 objects.

Letter is the part which travels from beginning till end of this story and thus makes it possible
Command Object helps in separating the creation and execution logic.
Antony (The Invoker)-
He is the most important character of this story. As nothing can happen without him. He is the one who decides when the command will be executed(remember DO IT). He is the invoker of command.
So, To murder someone Antony don't need to know how a murder is done(Although he knows). he just need to say DO IT and rest is done.

In Java terms to execute the command invoker just need to have Command object whose execute() method it will call to Invoke the command.

Command pattern separates the logic of creating a request and executing a request.

Antony has Command

Requestors (or Clients)

These are the people who came to Antony for getting their work done. Their requests actually changed to commands when Antony said DO IT.
Their work is to give all the details required for the execution in the letter. And to hand it over to Antony. The story starts from them. 
Client creates the Command object and then set this object in Invoker using setter method. 
Full Picture

 Command Pattern Class Diagram

In this case Antony does not want the command to complete till he is sure that everything is under control. So, although creation of letter happens early but its execution happens later.

Command Pattern is required when the command can't be executed as soon as it is created. And there is a separate entity or condition which controls the invocation of command(Antony in this case).

There could be more than one letter with antony when he decides time is appropriate for execution.

Invoker can have more than one command.

visit ApexInformatix.com for Online/Classroom course on Java and other technologies

Thursday, July 17, 2014

Decorator Pattern in Java

This is the story of "Sam, the billionaire". I like to translate all my stories in Java. So, you will also see Java version of this story.
Story begins...
Sam is owner of a Toy Company. Dolls made in his company are very famous.
Some of the popular Dolls

Java version-
Sam defines an interface Doll which defines all required features which a doll should have (make, price & description).
Whenever a new type of doll is introduced it implements Doll interface. And it has to implement all the methods defined in it.

Next Step...

To take his company a step forward he wants to introduce new features in his dolls.
  • Speech - Speaking doll, Singing doll, Nursery rhymes doll etc.
  • Motion - Walking doll, Running doll, Spinning doll etc.
  • Light - Doll with glowing eyes, mouth etc.
But he wants to keep these features customizable. Customer can choose one or more of these features and get a customized doll.

Sam decides to start making the dolls. So, he tries to figure out what all combinations are possible-
  1. Baby girl
  2. Baby girl which cries
  3. Baby girl which sings
  4. Baby girl which sings nursery rhymes
  5. Baby girl which walks
  6. Baby girl which cries and walks
  7. ...... And many more
Ok so, there are many possible combinations.
Java Version
To implement dolls with customizable features first thing that came into Sam's mind was inheritance. He made a class for each doll type which will implement Doll interface. Apart from implementing methods in Doll interface it added methods to give additional functionality specific to doll. 
e.g. SpeakingDoll class will implement Doll interface and will have addSpeech() method for additional functionality which will be called from make() method.

Class Diagram will look something like this.(Note- Not showing all classes due to space constraint)

There is a class explosion. Maintaining such a thing is going to be a big overhead.

Large no. of possible combinations. So, many dolls will have to be built and Sam is not sure all of them will be sold.

Class Explosion. Large number of classes will make the code difficult to maintain.

If a new feature has to be added in future e.g. multiple languages again there will be a lot of possible combinations.

Not all functionality can be foreseen, If a new feature is added in future new classes will be required.

If we have to change voice of speaking dolls all dolls with speech will have to be changed.

Any change in the existing functionality will impact many classes.

Finding the Solution...

He calls his team for a solution. Luckily one of the team member suggests a perfect solution.

Use of Decorator Pattern.

Lets try to understand this solution-
Make a doll when there is an order. Take the basic doll e.g. Baby girl, Baby boy etc. based on the requirement and add features to it as per client's demand.

Add features dynamically at runtime.

Lets take example of Singing baby girl to understand the solution. 
Baby girl doll is build in factory. Sound Engineer use this doll and add singing feature to it.
If any other feature is also required e.g. walking then this doll is passed to the motion engineer who adds the feature on the doll. So, one feature is built on the top of the other. Something like this.
As each feature has to be added at runtime we need a separate class for each feature e.g. SingingDoll with method addSinging() which will add the required feature.

Sound engineer required a baby girl doll to add singing feature on it similarly SingingDoll object needs BabyGirl object on the top of which it can add singing feature.
SingingDoll has BabyGirl
  • Using composition we can add additional features to an object. 
In future requirement can change and client may want Baby boy doll or any other doll with singing feature. If we add an object of type Doll to SingingDoll we will not have to worry about the type of doll as all dolls implement Doll interface.
So, we can decide at runtime what type of doll we want and can add its object to SingingDoll
  • Using inheritance we can change the type of an object at runtime.
So, using the power of composition and inheritance together we can add the functionality dynamically. Any feature class will look like this.

Works well for SingingDoll but in future we may want to add another feature on the top of it e.g. Crying

Design will be something like this in that case-

In that case, we will need CryingDoll class to wrap around object of SingingDoll class. i.e.
CryingDoll has SingingDoll. Singing Doll has BabyGirlDoll.
Like any Feature class CryingDoll class has object of type Doll. But we have to add SingingDoll object(another Feature).
If SingingDoll too implements Doll interface it will not be a problem.

If Feature class implements Doll interface we can add any Feature on the top of the other.

Now doll object in Feature class can be used to access the basic functionality of underlying object and any new feature can be added before or after it.

To make design more flexible we add a superclass FeatureDecorator which all feature classes will extend. Any additional behaviour can be added in subclass.

This is example of Decorator Pattern in Java.

  • To add feature to a component at runtime Decorator class is used.
  • This class implements interface of the component and also has object having type of component's interface.
  • So, object of any component can be added to a Decorator.
  • Since Decorator also implements component's interface, one Decorator can also be added to other.
This is how Decorator Pattern works.
Decorator object has another Decorator object or Component object.
Component object is at the core.

  • Client has access to the outermost Decorator object.
  • Decorator object have full access to the functionality of underlying Decorator or Component. Using its object it can call the functionality before or after its own functionality. This helps in adding or modifying underlying functionality.
This is how method call works in Decorator Pattern-

Client calls the method of outermost Decorator class. This method calls the method of underlying Decorator/Component using the object it has. It can use output of this method to add some additional behaviour to it.

Using this lets try to calculate the cost of a Singing Baby Doll-
Outermost Object is SingingDoll(Decorator). From cost() method of SingingDoll we can call doll.cost(). This will give cost of underlying doll object which is actually BabyDoll(Component). Now we can add additional cost of singing feature and return to the user.

Now that our pattern is ready its time to write some Java Code-
Main Interface-

Main components (Types of Dolls)-
It implements Doll interface and its methods.

BabyGirl implementation-

BabyBoy implementation-

Abstract Decorator class-
It was simple till this point. Now we need to add Decorator superclass so that we can add features dynamically.

This interface has an object of type Doll and it also implements Doll interface.

ConcreteDecorator class-

SingingDoll class extends this class.

Methods of SingingDoll calls method of doll object and add its own functionality before or after it.

Here functionality added by SingingDoll class is outlined in green color in each method.

SingingDoll object gets access to the underlying doll object functionality and state. It can add or modify it as per requirement.

Lets use this code to create a Singing Baby Girl doll.

Create object of BabyGirl and pass it to SingingDoll object.

output of singing.make()-
Baby Girl is Ready
Singing feature added

We call make method of SingingDoll from which make method of underlying doll object(BabyGirl) is called.

Similarly, when we call cost() method we get cost of BabyGirl (100)+Singing(50)

If we change the underlying object to BabyBoy-

Methods of BabyBoy will be called.
output of singing.make()-
Baby Boy is Ready
Singing feature added
when we call cost() method we get cost of BabyBoy (60)+Singing(50)

To add any new feature e.g. Crying to it Just need to pass singing object to the constructor of Crying class(which extends FeatureDecorator)
We can add as many features as we want. We can also have different types of decorators e.g. SpeechDecorator, MotionDecorator, LightDecorator etc.
But they should follow rules of Decorator pattern-

  • Decorator class should be of same type as the component to which they add functionality. So, they implement the interface which the component implement.
  • Decorator class wrap the object of the component and add functionality to it. So, they have an object of the component. Type of this object is Interface which component implement. This provide flexibility to add another Decorator on top (as all Decorators are also of same type)
  • There can be many layers of Decorator wrapped around component. Each Decorator add or modify the existing functionality.
  • Methods of Decorator call methods of component (using the object they have) either before or after their implementation. This adds or modifies the functionality.

Class Diagram of Decorator Pattern-

Decorator Pattern is a complicated pattern so it should be used wisely else it makes the code hard to understand and maintain.
In Java, I/O Stream uses Decorator Pattern.

Thanks to Decorator Pattern, Sam is a billionaire today.

visit ApexInformatix.com for Online/Classroom course on Java and other technologies

Friday, July 11, 2014

Observer Pattern in Java

Lizza decides to get a new dress for her 18th birthday party. She goes online to her favourite website fashionworld.com and selects a perfect Red dress. But oops its out of stock.

She tries to find another dress but there is nothing that can replace it. So, she goes back to the dress, registers her email id and click on "Notify Me" button.

You must be wondering why am I telling you story of Red Dress? Reason is "Notify Me" button is an example of Observer Pattern.

Here is how "Notify Me" button works? As soon as the dress will be in stock she will be notified via an email.
Similarly, there could be other users waiting for the Red Dress. As shown below user1, user2 and user3 have registered for notification just like Lizza. So, they will be notified once dress is available.

User4 is not interested in Red Dress so, she never registered by clicking "Notify Me" button. No email will be sent to her when the dress is 'In Stock'

If user1 finds another dress and is no longer interested in the Red Dress. Then user1 can get the registration removed. In this case she will no longer be informed when dress is available.

Lets dive into Observer Pattern now.

  1. All the users who registered for notification in the above case are Observers (user1, user2, user3).
  2. The subject of their observation is Red Dress. So, Red Dress is Observable.
 There is one Red dress but many users interested in it.

Observer Pattern defines one to many relationship between Observable and observers

When the state of dress changes from 'Out of stock' to 'in stock' all users are notified.

When Observable changes state all Observers are notified

User4 is not registered hence he is not an observer in this case.
If User1 gets her registration removed later. She will not remain an Observer in that case and will not be notified.

Observers subscribe for an Observable. Observers can unsubscribe at any time

Time to write Java code to implement this pattern-

What functionalities will be required in an Observable?
  • Register observer
  • Remove observer
  • Notify observer on state change

Normal RedDress class will look like this-

To become observable RedDress need to implement functionalities of Observable (point 1 below).

RedDress maintains a list of all registered users or Observers (point 2 below)
A new user is added to the users list from addObserver() method (point 3 below)
user is removed from the list from removeObserver() method is called (point 4 below)
At any point of time RedDress will have the list of all the users who need to be notified.
'Observable maintains a list of Observers'

notifyObserver() method has responsibility of informing all the observers about the change.(point 5 below)
Any change to inStock will happen from the setter setInStock(). Whenever, this happens all the users need to be notified simply by calling notifyObserver method (point 6 below)

Now how will Observer look like?

Observable need to update all the Observers. So, Observer should have a method update() which Observable can call to notify about the change.

So, notifyObserver() method of Observable will call update() method of all Observers.

If a user has to become an Observer it will implement Observer functionality (Point 1 below).
From update method User can do something when state of Observable is changed. In this case buyDress() is called. (Point 2 below)

Once, user calls buyDress() he is not interested in any status change of RedDress. So, it calls unsubscribe() to get removed from the observer list of RedDress (Point 3 below). 
For this removeObserver of Observable need to be called. User keeps a reference of Observable so that it can call removeObserver when required.

Here, User is not doing much with the status of Observable. But in some cases user might need to know the changed current status. e.g. if user need to know the change in price of the dress etc.

    • In such a case either the state of Observable is passed as parameter to the update method.        
      update(int price); 
              This is PUSH approach as the state is pushed from Observable to Observer.
    • Or Observer can use reference of Observable to call getters in Observable and get the state.          e.g. Observer can call isInStock() or getPrice() from update() method. 
               This is PULL approach as Observer pulls the state from Observable.

    What we achieved?
    We were able to separate the logic of Observer and Observable and make them independent of each other. Now user can has its own independent functionality e.g. goToWork(), driveCar() or any other functionality.
    And any change to that will not impact our Observable. Vice versa is also true any change to Observable will not impact Observer.
     Due to use of Interfaces, Observable and Observers are loosely coupled.

    In future if we decide that User should not implement Observer Interface no code change is required in Observable class as it uses Observer Interface and not the concrete class.

    Similarly any new class can become an Observer by simply implementing Interface and it will not impact Observable.

    Observer & Observable are loosely coupled. Change to one will not impact other

    Based on this example lets create Class Diagram for above example-

    Observer Pattern Class Diagram

    visit ApexInformatix.com for Online/Classroom course on Java and other technologies