Sunday, 27 November 2016

Chain of Responsibility Design Pattern

Decoupling is one of the prominent mantras in software engineering.

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.

In a chain of objects, the responsibility of deciding who to serve the request is left to the objects participating in the chains.

                          

รจIt is similar to ‘passing the question in a quiz scenario’. When the quiz master asks a question to a person, if he doesn’t knows the answer, he passes the question to next person and so on. When one person answers the question, the passing flow stops. Sometimes, the passing might reach the last person and still nobody gives the answer.

Currency.java
public class Currency {

     private intamount;

     public Currency(intamt){
           this.amount = amt;
     }

     public intgetAmount(){
           return this.amount;
     }
}

DispenseChain.java
public interface DispenseChain {

     voidsetNextChain(DispenseChain nextChain);
    
     void dispense(Currency cur);
}

Rupees1000Dispenser.java
public class Rupees1000Dispenser implements DispenseChain {

     private DispenseChain chain;
    
     @Override
     public voidsetNextChain(DispenseChain nextChain) {
           this.chain=nextChain;
     }

     @Override
     public voiddispense(Currency cur) {
           if(cur.getAmount() >= 1000){
                int num = cur.getAmount()/1000;
                int remainder = cur.getAmount() % 1000;
                System.out.println("Dispensing "+num+" Rs. 1000 note");
                if(remainder !=0) this.chain.dispense(newCurrency(remainder));
           } else {
                this.chain.dispense(cur);
           }
     }
}

Rupees500Dispenser.java
public class Rupees500Dispenser implements DispenseChain{

     private DispenseChain chain;

     @Override
     public voidsetNextChain(DispenseChain nextChain) {
           this.chain=nextChain;
     }

     @Override
     public voiddispense(Currency cur) {
           if(cur.getAmount() >= 500){
                int num = cur.getAmount()/500;
                int remainder = cur.getAmount() % 500;
                System.out.println("Dispensing "+num+" Rs. 500 note");
                if(remainder !=0) this.chain.dispense(newCurrency(remainder));
           } else {
                this.chain.dispense(cur);
           }
     }
}

Rupees100Dispenser.java
public class Rupees100Dispenser implements DispenseChain {

     private DispenseChain chain;
    
     @Override
     public voidsetNextChain(DispenseChain nextChain) {
           this.chain=nextChain;
     }

     @Override
     public voiddispense(Currency cur) {
           if(cur.getAmount() >= 100) {
                int num = cur.getAmount()/100;
                int remainder = cur.getAmount() % 100;
                System.out.println("Dispensing "+num+" Rs. 100 note");
                if(remainder !=0) this.chain.dispense(newCurrency(remainder));
           } else {
                this.chain.dispense(cur);
           }
     }

}

ATMDispenseChain.java
public classATMDispenseChain {

     privateDispenseChain chainStart;

     publicATMDispenseChain() {
          
           // initialize the chain
           this.chainStart = new Rupees1000Dispenser();
           DispenseChain chain500 = new Rupees500Dispenser();
           DispenseChain chain100 = new Rupees100Dispenser();

           // set the chain of responsibility
           chainStart.setNextChain(chain500);
           chain500.setNextChain(chain100);
     }
    
     publicDispenseChain getChainStart() {
           return chainStart;
     }
}


TestChainPattern.java
importjava.util.Scanner;

public classTestChainPattern {

     public static voidmain(String[] args) {
           ATMDispenseChain atmDispenser = new ATMDispenseChain();
           int amount = 0;
           System.out.println("Enter amount to dispense");

           Scanner input = new Scanner(System.in);
           amount = input.nextInt();

           if (amount % 100 != 0) {
                System.out.println("Amount should be in multiple of 100s.");
                return;
           }

           // process the request
           atmDispenser.getChainStart().dispense(new Currency(amount));

           input.close();
     }
}


Chain of Responsibility Pattern Examples
ATM dispense machine.
Struts interceptor.

Usage of Chain of Responsibility Pattern in JDK
java.util.logging.Logger#log()
javax.servlet.Filter#doFilter()

Wednesday, 16 November 2016

Facade pattern

The facade pattern is a wrapper of many other interfaces in a result to produce a simpler interface. Facade hides the complexities of the system and provides an interface to the client from where the client can access the system easily.
A facade is an object that provides a simplified interface to a larger body of code, such as a class library.





Example: This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).

/* Complex parts */

class CPU {
      public void freeze() {
            ...
      }
      public void jump(long position) {
            ...
      }
      public void execute() {
            ...
      }
}

class Memory {
      public void load(long position, byte[] data) {
            ...
      }
}

class HardDrive {
      public byte[] read(long lba, int size) {
            ...
      }
}

/* Facade */

class ComputerFacade {
      private CPU processor;
      private Memory ram;
      private HardDrive hd;

      public ComputerFacade() {
            this.processor= new CPU();
            this.ram = new Memory();
            this.hd = new HardDrive();
      }

      public void start() {
            processor.freeze();
            ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
            processor.jump(BOOT_ADDRESS);
            processor.execute();
      }
}

/* Client */

class Facade {
      public static void main(String[] args) {
            ComputerFacade computer = newComputerFacade();
            computer.start();
      }
}


Points to remember about faรงade design pattern:
1. Wrap a poorly designed collection of APIs with a single well-designed API.
2. Reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
3. Facade design pattern is more like a helper for client applications; it doesn’t hide subsystem interfaces from the client. Whether to use Facade or not is completely dependent on client code.
4. Facade design pattern can be applied at any point of development, usually when the number of interfaces grows and system gets complex.
5. Subsystem interfaces are not aware of Facade and they shouldn’t have any reference of the Facade interface.

We can use Factory pattern with Facade to provide better interface to client systems.

Thursday, 3 November 2016

What is Interceptor in Struts2?

Interceptor is an object that is invoked at the preprocessing and post processing of a request. In Struts 2, interceptor is used to perform operations such as validation, exception handling, internationalization, displaying intermediate result etc.

ActionInvocation is responsible to encapsulate Action classes and interceptors and to fire them in order. The most important method for use in ActionInvocation is invoke() method that keeps track of the interceptor chain and invokes the next interceptor or action. This is the best example of Chain of Responsibility pattern in J2EE.

Interceptors are conceptually the same as servlet filters or the JDKs Proxy class.

Advantage of interceptors
Interceptor plays a crucial role in achieving high level of separation of concerns.
Providing preprocessing/post processing logic before/after the action is called.

Catching exceptions so that alternate processing can be performed.

Pluggable if we need to remove any concern such as validation, exception handling, logging etc. from the application, we don't need to redeploy the application. We only need to remove the entry from the struts.xml file.

Which design pattern is implemented by Struts2 interceptors?
Struts2 interceptors are based on intercepting filters design pattern

The invocation of interceptors in interceptor stack closely resembles Chain of Responsibility design pattern.
Related Posts Plugin for WordPress, Blogger...