Monday, December 29, 2014

Command Design Pattern

Design Pattern > Behavioral Design Pattern > Command Design Pattern

In Command design pattern a request is pass to an invoker as an Object, here invoker does not knows to serve the request but uses the command to perform an action.

Benefits of Using Command Pattern :
. it hides the details of the actions that needs to be performed, so that the client code does not need to be concerned about the details when it needs to execute the actions. The client code just needs to tell the application to execute the command that was stored.
. It's easy to add new comands without changing the existing classes.

Key Terms :
Command - Interface with concrete method declaration
ConcreteCommand -

  • Implements Command
  • Set Receiver in it's method or constructor
  • Call Receiver's method in execute()

Receiver -

  • Define Actions to be performed

Invoker - Command Object passed to Invoker and it instructs the command to perform an action.

  • Set Command object in it's method or constructor
  • Call execute on Command object

Client -

  • Create Receiver object
  • Create Concreate Command object(s)
  • Create invoker object and call it's method


Java Implementation :
     In the above key terms you have already seen the Pseudocode. Now, we will see the complete implementation in Java

// Command Interface
public interface Order {

void execute();
}

// ConcreteCommand
public class StockBuy implements Order {

private StockTrade stock;
public StockBuy(StockTrade trade){
stock = trade;
}
@Override
public void execute() {
// call receiver's method
stock.buy();
}

}

// ConcreteCommand
public class StockSell implements Order {

private StockTrade stock;
public StockSell(StockTrade trade){
stock = trade;
}
@Override
public void execute() {
// call receiver's method
stock.sell();
}

}

// Receiver class
public class StockTrade {

public void buy() {
System.out.println("buying stock");
}

public void sell() {
System.out.println("selling stock");
}

}

// Invoker Class
public class Broker {
Order order;
public Broker(Order odr){
order = odr;
}
void placeOrder(){
order.execute();
}
}

// Client Class
public class Client {

public static void main(String[] args) {
// Create Receiver object
StockTrade st = new StockTrade();
// Create Concreate Command object(s)
StockBuy sb = new StockBuy(st);
StockSell ss = new StockSell(st);
// Create invoker object
Broker bbuy = new Broker(sb);
Broker bsell = new Broker(ss);
// call invoker method
bbuy.placeOrder();
bsell.placeOrder();
}

}

is Invoker Optional In Command Pattern ?
As we know, java.lang.Runnable is one of the examples of command pattern where Thread class works as an invoker. We pass object of a Runnable class to Thread class and say start/run.

But we never create a client class which can invoke main thread.

So an invoker is not optional but it is not tightly coupled to client.

Tuesday, December 2, 2014

Chain of Responsibility Design Pattern


Design Pattern > Behavioral Design Pattern > Chain of Responsibility Design Pattern

Chain of responsibility helps to decouple sender of a request and receiver of the request with some trade-offs. Chain of responsibility is a design pattern where a sender sends a request to a chain of objects, where the objects in the chain decide themselves who to honor the request. If an object in the chain decides not to serve the request, it forwards the request to the next object in the chain.

Responsibility is outsourced. In a chain of objects, the responsibility of deciding who to serve the request is left to the objects participating in the chains.
The most usual example of a machine using the Chain of Responsibility is the vending machine coin slot: rather than having a slot for each type of coin, the machine has only one slot for all of them. The dropped coin is routed to the appropriate storage place that is determined by the receiver of the command.

Having so many design patterns to choose from when writing an application, it's hard to decide on which one to use, so here are a few situations when using the Chain of Responsibility is more effective:

  • More than one object can handle a command
  • The handler is not known in advance
  • The handler should be determined automatically
  • It’s wished that the request is addressed to a group of objects without explicitly specifying its receiver
  • The group of objects that may handle the command must be specified in a dynamic way

Example Java Code

Digit.java

package com.kmingle.chainofresponsibility;

public class Digit {

private int digit;
public Digit(int digit){
this.digit = digit;
}

public int getDigit() {
return digit;
}
}

Handler.java

package com.kmingle.chainofresponsibility;

public interface Handler {

public abstract void setNextHandler(Handler nextHandler);
public abstract void processRequest(Digit input);
}


NegativeHandler.java

package com.kmingle.chainofresponsibility;

public class NegativeHandler implements Handler{

private Handler nextHandler;

@Override
public void setNextHandler(Handler nxtHandler) {

nextHandler = nxtHandler;
}

@Override
public void processRequest(Digit input) {

if(input.getDigit() < 0){
System.out.println("handled by negative handler : "+ input.getDigit());
}
else {
nextHandler.processRequest(input);
}
}

}

PositiveHandler.java 

package com.kmingle.chainofresponsibility;

public class PositiveHandler implements Handler{

private Handler nextHandler;
@Override
public void setNextHandler(Handler nxtHandler) {
nextHandler = nxtHandler;
}

@Override
public void processRequest(Digit input) {
if(input.getDigit() > 0){
System.out.println("handled by positive handler : "+ input.getDigit());
}
else {
nextHandler.processRequest(input);
}
}

}

ZeroHandler.java 

package com.kmingle.chainofresponsibility;

public class ZeroHandler implements Handler{

private Handler nextHandler;
@Override
public void setNextHandler(Handler nxtHandler) {
nextHandler = nxtHandler;
}

@Override
public void processRequest(Digit input) {
if(input.getDigit() == 0){
System.out.println("handled by zero handler : "+ input.getDigit());
}
else {
nextHandler.processRequest(input);
}
}

}

Requester.java

package com.kmingle.chainofresponsibility;

public class Requester {
public static void main(String[] args) {
// configuration for request handler chains
Handler h1 = new Negativehandler();
Handler h2 = new Positivehandler();
Handler h3 = new Zerohandler();
h1.setNextHandler(h2);
h2.setNextHandler(h3);
// calling chain
h1.processRequest(new Digit(10));
h1.processRequest(new Digit(-10));
h1.processRequest(new Digit(0));
h1.processRequest(new Digit(20));
}

}

Output :

handled by positive handler : 10
handled by negative handler : -10
handled by zero handler : 0
handled by positive handler : 20

Total Pageviews