Thursday, November 5, 2015

Design Patterns - Command Pattern



https://dzone.com/articles/design-patterns-command
http://javapapers.com/design-patterns/command-design-pattern/

The following information is copied from the above links..


Image title



Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation.

java.lang.Runnable
javax.swing.Action


  • Command is an interface with execute method. It is the core of contract.
//Command
public interface Command{
  public void execute();
}


  • A Command implementation’s instance creates a binding between the receiver and an action
//Concrete Command
public class LightOnCommand implements Command{
  //reference to the light
   Light light;
  public LightOnCommand(Light light){
     this.light = light;
}
  public void execute(){
     light.switchOn();
}
}



//Concrete Command
public class LightOffCommand implements Command{
  //reference to the light
  Light light;
  public LightOffCommand(Light light){
    this.light = light;
  }
  public void execute(){
    light.switchOff();
  }
}


  • Receiver is the object that knows the actual steps to perform the action.
Receiver Class

//Receiver

public class Light{
  private boolean on;
  public void switchOn(){
    on = true;
  }
  public void switchOff(){
    on = false;
  }
}

  • An invoker instructs the command to perform an action.

//Invoker
public class RemoteControl{
  private Command command;
  public void setCommand(Command command){
    this.command = command;
  }
  public void pressButton(){
    command.execute();
  }
}

  • A client creates an instance of a command implementation and associates it with a receiver.
//Client
public class Client{
  public static void main(String[] args)    {
    RemoteControl control = new RemoteControl();
    Light light = new Light();
    Command lightsOn = new LightsOnCommand(light);
    Command lightsOff = new LightsOffCommand(light);
    //switch on
    control.setCommand(lightsOn);
    control.pressButton();
    //switch off
    control.setCommand(lightsOff);
    control.pressButton();
  }
}



Monday, November 2, 2015

Design Patterns

Mediator


Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which handles all the communications between different classes and supports easy maintainability of the code by loose coupling.
Ex  Arport Control Tower


Chain of Responsibility



The chain of responsibility pattern creates a chain of receiver objects for a request. This pattern decouples sender and receiver of a request based on type of request. This pattern comes under behavioral patterns.
In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the request then it passes the same to the next receiver and so on.

Ex: timesheet approval

Template

In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can overrides the method implementations as per need basis but the invocation is to be in the same way as defined by an abstract class.  The template method pattern is a very good example when to make a method as final.

Provide an abstract definition for a method or a class and redefine its behavior later or on the fly without changing its structure.


Observer


Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.

Observer pattern uses three actor classes. Subject, Observer and Client. Subject, an object having methods to attach and de-attach observers to a client object.

http://javapapers.com/design-patterns/observer-design-pattern/
http://www.tutorialspoint.com/design_pattern/observer_pattern.htm


In observer design pattern multiple observer objects registers with a subject for change notification. When the state of subject changes, it notifies the observers. Objects that listen or watch for change are called observers and the object that is being watched for is called subject.

Pattern involved is also called as publish-subscribe pattern. Model view controller (MVC) architecture’s core uses the observer design pattern

Subject provides interface for observers to register and unregister themselves with the subject.
Subject knows who its subscribers are.
Multiple observers can subscribe for notifications.
Subject publishes the notifications.
Subject just sends the notification saying the state has changed. It does not pass any state information.

Once the notification is received from subject, observers call the subject and get data that is changed.




State

In State pattern an object behavior changes based on its state. 
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

An object's behavior change is represented by its member classes, which share the same super class.Ex: My role as Technical Manager, Lead, and Architect http://javapapers.com/design-patterns/state-design-pattern/



Command



 A request is wrapped under a object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and pass the command to the corresponding object and that object executes the command.

Streamlize objects by providing an interface to encapsulate a request and make the interface implemented by subclasses in order to parameterize the clients.


Ex:  java.lang.Runnable and javax.swing.Action

Design Patterns - Chain Of Responsibility




Links for reading:

http://javapapers.com/design-patterns/chain-of-responsibility-design-pattern/
https://dzone.com/articles/design-patterns-uncovered-chain-of-responsibility

Copying information from Above here...


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.


  • Sender will not know which object in the chain will serve its request.
  • Every node in chain will have the responsibility to decide, if they can serve the request.
  • If node decides to forward the request, it should be capable of choosing the next node and forward it.
  • There is a possibility where none of the node may serve the request.
Example: 
1. Exception Handling
2. Servlet Filters
3. java.util.Logging
4. Typical Finance Dept (Associate --> Manager --> Director Budget approval)

There may be scenarios where a node is capable of solving the request but may not get a chance for it. Though there is a candidate who can solve the problem, but since nobody forwarded the request to it, it was not given a chance to serve and final result is the request goes unattended failure. This happens because of improper chain sequence. A chain sequence may not be suitable for all scenarios.


In object oriented design generally, every object is responsible for all its behavior. Behavior of an object is not transferred to other objects and is enclosed within itself. In chain of responsibility, some percentage of behavior is offloaded to third party objects.


Example - 1

Chain.java

This is the interface that acts as a chain link.
package com.javapapers.designpattern.chainofresponsibility;

public interface Chain {

 public abstract void setNext(Chain nextInChain);
 public abstract void process(Number request);
}

Number.java

This class is the request object.
package com.javapapers.designpattern.chainofresponsibility;

public class Number {
 private int number;

 public Number(int number) {
  this.number = number;
 }

 public int getNumber() {
  return number;
 }

}

NegativeProcessor.java

This class is a link in chain series.
package com.javapapers.designpattern.chainofresponsibility;

public class NegativeProcessor implements Chain {

 private Chain nextInChain;

 public void setNext(Chain c) {
  nextInChain = c;
 }

 public void process(Number request) {
  if (request.getNumber() < 0) {
   System.out.println("NegativeProcessor : " + request.getNumber());
  } else {
   nextInChain.process(request);
  }
 }
}

ZeroProcessor.java

This class is another link in chain series.
package com.javapapers.designpattern.chainofresponsibility;

public class ZeroProcessor implements Chain {

 private Chain nextInChain;

 public void setNext(Chain c) {
  nextInChain = c;
 }

 public void process(Number request) {
  if (request.getNumber() == 0) {
   System.out.println("ZeroProcessor : " + request.getNumber());
  } else {
   nextInChain.process(request);
  }
 }
}

PositiveProcessor.java

This class is another link in chain series.
package com.javapapers.designpattern.chainofresponsibility;

public class PositiveProcessor implements Chain {

 private Chain nextInChain;

 public void setNext(Chain c) {
  nextInChain = c;
 }

 public void process(Number request) {
  if (request.getNumber() > 0) {
   System.out.println("PositiveProcessor : " + request.getNumber());
  } else {
   nextInChain.process(request);
  }
 }
}

TestChain.java

This class configures the chain of responsibility and executes it.
package com.javapapers.designpattern.chainofresponsibility;

public class TestChain {
 public static void main(String[] args) {
  //configure Chain of Responsibility
  Chain c1 = new NegativeProcessor();
  Chain c2 = new ZeroProcessor();
  Chain c3 = new PositiveProcessor();
  c1.setNext(c2);
  c2.setNext(c3);

  //calling chain of responsibility
  c1.process(new Number(99));
  c1.process(new Number(-30));
  c1.process(new Number(0));
  c1.process(new Number(100));
 }
}



Example -2 

Email Processor

//Handler
This will be an interface which exposes primarily two methods.
One for specifying the next object and the other for processing the request.


public interface EmailHandler{

//reference to the next handler in the chain
public void setNext(EmailHandler handler);

//handle request
public void handleRequest(Email email);

}


// Business Email
//This is one of the chain of objects

public class BusinessMailHandler implements EmailHandler{
         private EmailHandler next;


         public void setNext(EmailHandler handler){
         next = handler;
        }


        public void handleRequest(Email email){
            if(!email.getFrom().endsWith("@businessaddress.com"){
               next.handleRequest(email);
            }else{
           //handle request
          (move to correct folder)
       }
     }
}


//This is one of the chain of objects
public class GMailHandler implements EmailHandler{
     private EmailHandler next;
   
     public void setNext(EmailHandler handler){
          next = handler;
     }

     public void handleRequest(Email email) {
      
         if(!email.getFrom().endsWith("@gmail.com"){
              next.handleRequest(email);
         }else{
         //handle request
        //(move to correct folder)
          }
      }
}


//This is the processor class which handles the objectsone of the chain of objects

public class EmailProcessor{
     //maintain a reference to the previous handler so we can add the
     //next one
     private EmailHandler prevHandler;

      public void addHandler(EmailHandler handler){
          if(prevHandler != null){
               prevHandler.setNext(handler);
          }
           prevHandler = handler;
     }
}

//email client
public class EmailClient{
             private EmailProcessor processor;
             //
             public EmailClient(){
                  createProcessor();
             }


            private void createProcessor(){
                  processor = new EmailProcessor();
                  processor.addHandler(new BusinessMailHandler());
                  processor.addHandler(new PersonalMailHandler());
            }


           public void addRule(EmailHandler handler){
                  processor.addHandler(handler);
           }


            public void emailReceived(Email email){
                  processor.handleRequest(email);
           }


           public static void main(String[] args){
                EmailClient client = new EmailClient();
           }


}