Friday 29 May 2015

State Design Pattern Implementation

State Design Pattern


Question : - What is State Design Pattern?
This design pattern also falls under Behavioral design pattern. This pattern helps to change behavior of an object based on the object’s state. In this pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

As per GOF:- “Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.”

Question:- How State pattern works?
Answer : -
  • We can define a context object, whose behavior varies as its state object changes.
  • We can define an object that represent various states.
Question : - When to use State design pattern?
Answer:- If we have the requirement like if we want to remember the state of the object which is mainly happening in any animated game or while making softwares for any DVD player or music players then we can proceed with this design pattern.

b) State design pattern in Java :-
  • javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle)
We will see an example of a new Pan Card application request. Here we will follow the below rules.
  • State changes or operation will be declared as interface. Actual implementations will have the particular/specific states with reference to the next required state.
  • State context will be responsible for instantiating the state with the initial state. 
  • When we invoke the first operation, it will keep moving to the different states for each execution till final state reaches.

State.java

package com.gaurav.designpattern.state;
/**
 * @author Gaurav
 *
 */
public interface State {
public void execute(StateContext context);
}

StateContext.java

package com.gaurav.designpattern.state;
/**
 * @author Gaurav
 *
 */
public class StateContext {
State state = null;
   public StateContext(State state){
       this.setState(new PanCardApplication());
   }
   public void setState(State state){
       this.state = state;
   }
 
   public void requestLifeCycle(){
       state.execute(this);
   }
}

PanCardApplication.java

package com.gaurav.designpattern.state;
/**
 * @author Gaurav
 *
 */
public class PanCardApplication implements State{
public void execute(StateContext context){
System.out.println("Request for new pan card accepted and acknowledgement generated!!");
context.setState(new PanCardVerification());
}
}


PanCardVerification.java

package com.gaurav.designpattern.state;
/**
 * @author Gaurav
 *
 */
public class PanCardVerification implements State{
public void execute(StateContext context){
System.out.println("Document submitted for new Pan Card are verified.");
context.setState(new PanCardAllotment());
}
}

PanCardAllotment.java

package com.gaurav.designpattern.state;
/**
 * @author Gaurav
 *
 */
public class PanCardAllotment implements State{
public void execute(StateContext context){
System.out.println("A new pan card is alloted for the given request.");
context.setState(new PanCardDelivery());
}
}


PanCardDelivery.java

package com.gaurav.designpattern.state;
/**
 * @author Gaurav
 *
 */
public class PanCardDelivery implements State{
public void execute(StateContext context){
System.out.println("A new Pan Card is delivered to the intended recipient.");
}
}


StateDesignPatternDemo.java

package com.gaurav.designpattern.state;
/**
 * @author Gaurav
 *
 */
public class StateDesignPatternDemo {
public static void main(String[] args) {
/**Creation of the state context for the request.*/
StateContext context = new StateContext(new PanCardApplication());

/**Invoking all the required operation for PAN CARD from state context. */
context.requestLifeCycle();
context.requestLifeCycle();
context.requestLifeCycle();
context.requestLifeCycle();
}
}

Result:-

Request for new pan card accepted and acknowledgement generated!!
Document submitted for new Pan Card are verified.
A new pan card is alloted for the given request.
A new Pan Card is delivered to the intended recipient.

Tuesday 12 May 2015

Observer Design Pattern Implementation

Observer Design Pattern

Question :- What is Observer Design Pattern?
Answer :- This design pattern also falls under Behavioral design pattern. This(Observer) pattern defines one-to-many dependency means it maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
The participants which involves in this design pattern are :
Subject :- Which contains a list of Observers in order to notify of any change in it's state. It should provide methods using which observers can register and unregister themselves.
Observer :- Dependent items which is listening subject and registering or unregistering based on the notification.

According to GoF, observer pattern says that;
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Question :- When to use Observer design pattern?
Answer :- If we have the requirement like in few scenario's watching for changes and if changes are available notifying to all the dependents elements then we should go with the pattern and this will give a flexibility where Observer and Observable both are loosely coupled.

Advantage of Observer Pattern:
  • Observer and Observable are loosely coupled.
  • Subject is only coupled with the Observer base class.
  • Observers registers themselves with the subject.
  • Subject published or broadcast events to all registered Observers.
  • All the observers are notified with a single event.
  • Client can configure types and number of observers.

Observer design pattern in Real world :- 
  • We have seen option in stock market trading i.e. While trading through any demat a/c if we need some notification during the rate change then if rate change is available, it will notify to all the required clients.
  • In few of the shopping site, if we are looking for some item and if that item size is not available then there is a option saying that Notify me which will help us to know whenever that item size will be available. 
b) Observer design pattern in Java :-
  • Observer and Observable are a part of util package. 
  • HttpSessionBindingListener is an example where Observer design pattern in used in Java API.
Example:- We will discuss about Stock market share index and rate changes in the below example and see how to place Observer Design Pattern on the below:

Observer.java
package com.gaurav.designpattern.observer;
/**
 * @author Gaurav
 *
 */
public interface Observer {
public void updating(Observable observable, Object arg);
}

Observable.java


package com.gaurav.designpattern.observer;
/**
 * @author Gaurav
 *
 */
public interface Observable {
public void notifyingObservers();
public void registeringObserver(Observer observer);
public void removingObserver(Observer observer);
}

Stock.java

package com.gaurav.designpattern.observer;
/**
 * @author Gaurav
 *
 */
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Stock implements Observable {
private List<Observer> observers;
private boolean isStockChanged;

private float hyundai;
private float maruti;

public Stock() {
observers = new ArrayList<Observer>();

}

public void registeringObserver(Observer observer) {
if (observer != null && observer instanceof Observer) {
this.observers.add(observer);
}

}

public void removingObserver(Observer observer) {
if (observer != null && observer instanceof Observer) {
this.observers.remove(observer);
}

}
public void notifyingObservers() {
Iterator<Observer> observerIterator = this.observers.listIterator();
while (observerIterator.hasNext()) {
Observer observer = observerIterator.next();
observer.updating(this, null);
}

}

public float getHyundai() {
return hyundai;
}

public void setHyundai(float hyundai) {
if (this.hyundai != hyundai) {
this.isStockChanged = true;
this.hyundai = hyundai;
}
this.setStockChanged();
}

public float getMaruti() {
return maruti;
}

public void setMaruti(float maruti) {
if (this.maruti != maruti) {
this.isStockChanged = true;
this.maruti = maruti;
}
this.setStockChanged();
}

public void setStockChanged() {
this.notifyingObservers();
}

}


Publish.java


package com.gaurav.designpattern.observer;
/**
 * @author Gaurav
 *
 */
public interface Publish {
public void publishing(String message);
}


MessagePropagator.java

package com.gaurav.designpattern.observer;
/**
 * @author Gaurav
 *
 */
import java.util.Calendar;

public class MessagePropagator implements Observer,Publish{
public void updating(Observable observable, Object arg) {
     Stock stock = (Stock)observable;
     String message = "Hyundai Stock change details are :"+stock.getHyundai()+" and Maruti :"
                         +stock.getMaruti()+" at "+Calendar.getInstance().getTime();
     this.publishing(message);
  }
 
  public void publishing(String msg) {
  System.out.println(msg);
    
  }

}

ObserverDesignPatternDemo.java


package com.gaurav.designpattern.observer;
/**
 * @author Gaurav
 *
 */
public class ObserverDesignPatternDemo {
public static void main(String[] args) {
Stock stock = new Stock();
MessagePropagator messagePropagator = new MessagePropagator();

stock.registeringObserver(messagePropagator);

stock.setHyundai(11);
stock.setMaruti(26);

}
}


Result:-

Hyundai Stock change details are :11.0 and Maruti :0.0 at Tue May 12 14:20:27 IST 2015
Hyundai Stock change details are :11.0 and Maruti :26.0 at Tue May 12 14:20:27 IST 2015