Jul 3, 2013

Best tutorial - Java Design patterns (Part 3) - Behavioral Design Patterns


Chain of Responsibility

Motivation

In writing an application of any kind, it often happens that the event generated by one object needs to be handled by another one. And, to make our work even harder, we also happen to be denied access to the object which needs to handle the event. In this case there are two possibilities: there is the beginner/lazy approach of making everything public, creating reference to every object and continuing from there and then there is the expert approach of using the Chain of Responsibility.
The Chain of Responsibility design pattern allows an object to send a command without knowing what object will receive and handle it. The request is sent from one object to another making them parts of a chain and each object in this chain can handle the command, pass it on or do both. 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.
    Intent:
  • It avoids attaching the sender of a request to its receiver, giving this way other objects the possibility of handling the request too.
  • The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it.

Implementation

The UML diagram of classes below will help us understand better the way the Chain works.
hain of Responsability Implementation - UML Class Diagram
    In the diagram above some explanations are needed on what is the role of every class:
  • Handler - defines an interface for handling requests
    • RequestHandler - handles the requests it is responsible for
    • If it can handle the request it does so, otherwise it sends the request to its successor
  • Client - sends commands to the first object in the chain that may handle the command
Here is how sending a request works in the application using the Chain of Responsibility: the Client in need of a request to be handled sends it to the chain of handlers, which are classes that extend the Handler class. Each of the handlers in the chain takes its turn at trying to handle the request it receives from the client. If ConcreteHandler_i can handle it, then the request is handled, if not it is sent to the handler ConcreteHandler_i+1, the next one in the chain.
The classic example of the Chain of Responsibility's implementation is presented for us below:
public class Request { 
 private int m_value;
 private String m_description;

 public Request(String description, int value)
 {
  m_description = description;
  m_value = value;
 }

 public int getValue()
 {
  return m_value;
 }

 public String getDescription()
 {
  return m_description;
 }          
}

public abstract class Handler
{
 protected Handler m_successor;
 public void setSuccessor(Handler successor)
 {
  m_successor = successor;
 }

 public abstract void handleRequest(Request request);
}

public class ConcreteHandlerOne extends Handler
{
 public void handleRequest(Request request)
 {
  if (request.getValue() < 0)
  {           //if request is eligible handle it
   System.out.println("Negative values are handled by ConcreteHandlerOne:");
   System.out.println("\tConcreteHandlerOne.HandleRequest : " + request.getDescription()
       + request.getValue());
  }
  else
  {
   super.handleRequest(request);
  }
 }
 }

public class ConcreteHandlerThree extends Handler
{
 public void handleRequest(Request request)
 {
  if (request.getValue() >= 0)
  {           //if request is eligible handle it
   System.out.println("Zero values are handled by ConcreteHandlerThree:");
   System.out.println("\tConcreteHandlerThree.HandleRequest : " + request.getDescription()
       + request.getValue());
  }
        else
  {
   super.handleRequest(request);
  }
 }
}

public class ConcreteHandlerTwo extends Handler
{
 public void handleRequest(Request request)
 {
  if (request.getValue() > 0)
  {           //if request is eligible handle it
   System.out.println("Positive values are handled by ConcreteHandlerTwo:");
   System.out.println("\tConcreteHandlerTwo.HandleRequest : " + request.getDescription()
       + request.getValue());
  }
        else
  {
   super.handleRequest(request);
  }
 }
}

public class Main 
{
 public static void main(String[] args) 
 {
  // Setup Chain of Responsibility
  Handler h1 = new ConcreteHandlerOne();
  Handler h2 = new ConcreteHandlerTwo();
  Handler h3 = new ConcreteHandlerThree();
  h1.setSuccessor(h2);
  h2.setSuccessor(h3);

  // Send requests to the chain
  h1.handleRequest(new Request("Negative Value ", -1));
  h1.handleRequest(new Request("Negative Value ",  0));
  h1.handleRequest(new Request("Negative Value ",  1));
  h1.handleRequest(new Request("Negative Value ",  2));
  h1.handleRequest(new Request("Negative Value ", -5));     
 }
}

Applicability & Examples

    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
-----

Command Pattern

“An object that contains a symbol, name or key that represents a list of commands, actions or keystrokes”. This is the definition of a macro, one that should be familiar to any computer user. From this idea the Command design pattern was given birth.
The Macro represents, at some extent, a command that is built from the reunion of a set of other commands, in a given order. Just as a macro, the Command design pattern encapsulates commands (method calls) in objects allowing us to issue requests without knowing the requested operation or the requesting object. Command design pattern provides the options to queue commands, undo/redo actions and other manipulations.

Intent

- encapsulate a request in an object
- allows the parameterization of clients with different requests
- allows saving the requests in a queue

Implementation

The idea and implementation of the Command design pattern is quite simple, as we will see in the diagram below, needing only few extra classes implemented.

Class diagram for the classic implementation of the command pattern (command design pattern)

The classes participating in the pattern are:
- Command - declares an interface for executing an operation;
- ConcreteCommand - extends the Command interface, implementing the Execute method by invoking the corresponding operations on Receiver. It defines a link between the Receiver and the action.
- Client - creates a ConcreteCommand object and sets its receiver;
- Invoker - asks the command to carry out the request;
- Receiver - knows how to perform the operations;

The Client asks for a command to be executed. The Invoker takes the command, encapsulates it and places it in a queue, in case there is something else to do first, and the ConcreteCommand that is in charge of the requested command, sending its result to the Receiver.

Here is a sample code of a classic implementation of this pattern for placing orders for buying and selling stocks:
Class diagram for a sample Stock Trading system iimplementing the command pattern.

The client creates some orders for buying and selling stocks (ConcreteCommands). Then the orders are sent to the agent (Invoker).The agent takes the orders and place them to the StockTrade system (Receiver). The agent keeps an internal queue with the order to be placed. Let's assume that the StockTrade system is closed each Monday, but the agent accepts orders, and queue them to be processed later on.
public interface Order {
    public abstract void execute ( );
}

// Receiver class.
class StockTrade {
    public void buy() {
        System.out.println("You want to buy stocks");
    }
    public void sell() {
        System.out.println("You want to sell stocks ");
    }
}

// Invoker.
class Agent {
    private m_ordersQueue = new ArrayList();

    public Agent() {
    }
   
    void placeOrder(Order order) {
        ordersQueue.addLast(order);
        order.execute(ordersQueue.getFirstAndRemove());
    }   
}

//ConcreteCommand Class.
class BuyStockOrder implements Order {
    private StockTrade stock;
    public BuyStockOrder ( StockTrade st) {
        stock = st;
    }
    public void execute( ) {
        stock . buy( );
    }
}

//ConcreteCommand Class.
class SellStockOrder implements Order {
    private StockTrade stock;
    public SellStockOrder ( StockTrade st) {
        stock = st;
    }
    public void execute( ) {
        stock . sell( );
    }
}

// Client
public class Client {
    public static void main(String[] args) {
        StockTrade stock = new StockTrade();
        BuyStockOrder bsc = new BuyStockOrder (stock);
        SellStockOrder ssc = new SellStockOrder (stock);
        Agent agent = new Agent();

        agent.placeOrder(bsc); // Buy Shares
        agent.placeOrder(ssc); // Sell Shares
    }
}


Applicability & Examples


The applicability of the Command design pattern can be found in these cases below:
- parameterizes objects depending on the action they must perform
- specifies or adds in a queue and executes requests at different moments in time
- offers support for undoable actions (the Execute method can memorize the state and allow going back to that state)
- structures the system in high level operations that based on primitive operations
- decouples the object that invokes the action from the object that performs the action. Due to this usage it is also known as Producer - Consumer design pattern.

The example of the meal order at a restaurant is a very good one when trying to explain better how the pattern works:
The waiter (Invoker) takes the order from the customer on his pad. The order is then queued for the order cook and gets to the cook (Receiver) where it is processed.
Class diagram for a sample Restaurant iimplementing the command pattern

In this case the actors in the scenario are the following: The Client is the customer. He sends his request to the receiver through the waiter, who is the Invoker. The waiter encapsulates the command (the order in this case) by writing it on the check and then places it, creating the ConcreteCommand object which is the command itself. The Receiver will be the cook that, after completing work on all the orders that were sent to him before the command in question, starts work on it. Another noticeable aspect of the example is the fact that the pad for the orders does not support only orders from the menu, so it can support commands to cook many different items.

Just the same way we can consider the example of an auto-repair shop. People come in with different cars that have different problems. The person at the front desk takes their information and places the car in a queue for repair. The information on the order is encapsulated in the paper the car owner will use when he comes back to pick up the fixed car. At some point the car will become the first item in the queue and the mechanic will repair it. Just as in the example above, the Client is the customer. The Invoker is the person at the front desk that takes the information on the car and its problems, the ConcreteCommand is the request for fixing the car and the Receiver is the mechanic.
   
The most used implementation of the command pattern is the one used to implement the undo options in applications:
 Class diagram for a sample calculator application implementing the command design pattern to manage the do/undo operatons.
Let's consider a calculator application. The application represents the Client. The calculator (Receiver) class is the main class used in the application to perform the commands. This might be as well the document class if we have a text editor application and we want to implement operations like copy/paste/etc.... When the application has to perform a command it creates the command and sent it to the invoker. The invoker calls the execute method of the command and adds it to a list containing all the commands. The execute method of the command delegate the call to the Calculator object. When undo operations are performed the invoker uses the list with all executed commands and calls for each one the unexecuted method. The redo operation works in the same manner.
---------

Interpreter

Motivation

The Interpreter is one of the Design Patterns published in the GoF which is not really used. Ussualy the Interpreter Pattern is described in terms of formal grammars, like it was described in the original form in the GoF but the area where this design pattern can be applied can be extended.

Intent

- Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
- Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design

Implementation

The implementation of the Interpreter pattern is just the use of the composite pattern applied to represent a grammar. The Interpreter defines the behaviour while the composite defines only the structure.

Interpreter Pattern Implementation - UML Class Diagram

Applicability & Examples

The Template Method pattern should be used:
- The Interpreter pattern is used exaustively in defining grammars, tokenize input and store it.
- A specific area where Interpreter can be used are the rules engines.
- The Interpreter pattern can be used to add functionality to the composite pattern.


Example 1 - Roman Numerals Convertor

The classical example fot the interpreter pattern is the one of interpreting the roman numerals. The expresion to be interpreted is a string which is put in the context. The context consists of the remaining unparsed Roman Numeral string and of the result of the numerral that are already parsed. The context is passed to one of four sub-interpreters based on the type of interpreting(Thousand, Hundred, Ten, One). This example it's using only TerminalExpressions.
The following participant classes are involved in this example: Context - keeps the current string that has to be parsed and the decimal that contains the conversion already done. Initially the context keeps the full string that has to be converted and 0 for the output decimal.

Expression - Consists of the interpret method which receives the context. Based on the current object it uses specific values for Thousand, Hundred, Ten, One and a specific multiplier.

ThousandExpression, HundredExpression, TenExpression, OneExpression (TerminalExpression) - Those classes are usued to define each specific expression. Ussualy, the TerminalExpression classes implement the interpret method. In our case the method is already defined in the base Expression class and each TerminalExpression class defines its behaviour by implmenting the abstract methods: one, four(), five(), nine(), multiplier(). It is a template method pattern.

Main(Client) - In our litle example this class is responsible to build the syntax tree representing a specific sentence in the language defined by the grammar. After the syntax tree is build the main method is invoking the interpret method.
public class Context {

    private String input;
    private int output;

    public Context(String input)
    {
      this.input = input;
    }

    public String getInput()
    {
      return input;
    }
    
    public void setInput(String input)
    {
      this.input = input; 
    }    

    public int getOutput()
    {
      return output;
    }

    public void setOutput(int output)
    {
      this.output = output;
    }    
 
}

public abstract class Expression {

    public void interpret(Context context)
    {
      if (context.getInput().length() == 0) 
        return;

      if (context.getInput().startsWith(nine()))
      {
        context.setOutput(context.getOutput() + (9 * multiplier()));
        context.setInput(context.getInput().substring(2));
      }
      else if (context.getInput().startsWith(four()))
      {
        context.setOutput(context.getOutput() + (4 * multiplier()));
        context.setInput(context.getInput().substring(2));
      }
      else if (context.getInput().startsWith(five()))
      {
        context.setOutput(context.getOutput() + (5 * multiplier()));
        context.setInput( context.getInput().substring(1));
      }

      while (context.getInput().startsWith(one()))
      {
        context.setOutput(context.getOutput() + (1 * multiplier()));
        context.setInput(context.getInput().substring(1));
      }
    }

    public abstract String one();
    public abstract String four();
    public abstract String five();
    public abstract String nine();
    public abstract int multiplier();
 
}

public class ThousandExpression  extends Expression{

    public String one() { return "M"; }
    public String four(){ return " "; }
    public String five(){ return " "; }
    public String nine(){ return " "; }
    public int multiplier() { return 1000; }
}

public class HundredExpression extends Expression{
    public  String one() { return "C"; }
    public  String four(){ return "CD"; }
    public  String five(){ return "D"; }
    public  String nine(){ return "CM"; }
    public  int multiplier() { return 100; }
}

public class TenExpression  extends Expression{
    public String one() { return "X"; }
    public String four(){ return "XL"; }
    public String five(){ return "L"; }
    public String nine(){ return "XC"; }
    public int multiplier() { return 10; }
}

public class OneExpression  extends Expression{
    public String one() { return "I"; }
    public String four(){ return "IV"; }
    public String five(){ return "V"; }
    public String nine(){ return "IX"; }
    public int multiplier() { return 1; }
}

public class MainInterpreter {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
       String roman = "MCMXXVIII";
       Context context = new Context(roman);

       // Build the 'parse tree' 
       ArrayList<Expression> tree = new ArrayList<Expression>();
       tree.add(new ThousandExpression());
       tree.add(new HundredExpression());
       tree.add(new TenExpression());
       tree.add(new OneExpression());

       // Interpret 
       for (Iterator it = tree.iterator(); it.hasNext();)
       {
        Expression exp = (Expression)it.next();
        exp.interpret(context);
       }

       System.out.println(roman + " = " + Integer.toString(context.getOutput()));
 }
}

------------

Iterator

Motivation

One of the most common data structures in software development is what is generic called a collection. A collection is just a grouping of some objects. They can have the same type or they can be all cast to a base type like object. A collection can be a list, an array, a tree and the examples can continue.

But what is more important is that a collection should provide a way to access its elements without exposing its internal structure. We should have a mechanism to traverse in the same way a list or an array. It doesn't matter how they are internally represented.

The idea of the iterator pattern is to take the responsibility of accessing and passing trough the objects of the collection and put it in the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated.

Intent

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

The abstraction provided by the iterator pattern allows you to modify the collection implementation without making any changes outside of collection. It enables you to create a general purpose GUI component that will be able to iterate through any collection of the application.

Implementation

Iterator Implementation - UML Class Diagram

Applicability & Examples

The iterator pattern allow us to:
  • access contents of a collection without exposing its internal structure.
  • support multiple simultaneous traversals of a collection.
  • provide a uniform interface for traversing different collection.

Example 1: This exmple is using a collection of books and it uses an iterator to iterate through the collection. The main actors are:
  • IIterator - This interface represent the AbstractIterator, defining the iterator
  • BookIterator - This is the implementation of Iterator(implements the IIterator interface)
  • IContainer - This is an interface defining the Agregate
  • BooksCollection - An implementation of the collection
Here is the code for the abstractions IIterator and IContainer:

interface IIterator
{
 public boolean hasNext();
 public Object next();
}

interface IContainer
{
 public IIterator createIterator();
}

And here is the code for concrete classes for iterator and collection. Please note that the concrete iterator is an nested class. This way it can access all the members of the collection and it is encapsulated so other classes can not access the BookIterator. All the classes are not aware of BookIterator they uses the IIterator:

class BooksCollection implements IContainer
{
 private String m_titles[] = {"Design Patterns","1","2","3","4"};

 public IIterator createIterator()
 {
  BookIterator result = new BookIterator();
  return result;
 }


 private class BookIterator implements IIterator
 {
  private int m_position;

  public boolean hasNext()
  {
   if (m_position < m_titles.length)
    return true;
   else
    return false;
  }
  public Object next()
  {
   if (this.hasNext())
    return m_titles[m_position++];
   else
    return null;
  }
 }
}


Example 2: Java collection framework
--------

Mediator Pattern

Motivation

In order to have a good object oriented design we have to create lots of classes interacting one with each other. If certain principles are not applied the final framework will end in a total mess where each object relies on many other objects in order to run. In order to avoid tight coupled frameworks, we need a mechanism to facilitate the interaction between objects in a manner in that objects are not aware of the existence of other objects.
Let's take the example of a screen. When we create it we add all sort of controls to the screen. This control need to interact with all the other control. For example when a button is pressed it must know if the data is valid in other controls. As you have seen if you created different applications using forms you don't have to modify each control class each time you add a new control to the form. All the operations between controls are managed by the form class itself. This class is called mediator.

Intent

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
 Mediator Implementation - UML Class Diagram

Implementation


Participants

The participants classes in this pattern are:
  • Mediator - defines an interface for communicating with Colleague objects.
  • ConcreteMediator - knows the colleague classes and keep a reference to the colleague objects.
  • - implements the communication and transfer the messages between the colleague classes
  • Colleague classes - keep a reference to its Mediator object
  • - communicates with the Mediator whenever it would have otherwise communicated with another Colleague.


Applicability

According to Gamma et al, the Mediator pattern should be used when:
  • a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.
  • reusing an object is difficult because it refers to and communicates with many other objects.
  • a behavior that's distributed between several classes should be customizable without a lot of subclassing.

Examples

Example 1 - GUI Libraries

The mediator example is one pattern that is already used in many applications. One of the examples is represented by the Dialog classes in GUI applications frameworks. A Dialog window is a collection of graphic and non-graphic controls. The Dialog class provides the mechanism to facilitate the interaction between controls. For example, when a new value is selected from a ComboBox object a Label has to display a new value. Both the ComboBox and the Label are not aware of each other structure and all the interaction is managed by the Dialog object. Each control is not aware of the existence of other controls.

-----------

Observer Pattern


Motivation

We can not talk about Object Oriented Programming without considering the state of the objects. After all object oriented programming is about objects and their interaction. The cases when certain objects need to be informed about the changes occured in other objects are frequent. To have a good design means to decouple as much as possible and to reduce the dependencies. The Observer Design Pattern can be used whenever a subject has to be observed by one or more observers.
Let's assume we have a stock system which provides data for several types of client. We want to have a client implemented as a web based application but in near future we need to add clients for mobile devices, Palm or Pocket PC, or to have a system to notify the users with sms alerts. Now it's simple to see what we need from the observer pattern: we need to separate the subject(stocks server) from it's observers(client applications) in such a way that adding new observer will be transparent for the server.

Intent

  • Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Observer Design Pattern Implementation - UML Class Diagram

Implementation
The participants classes in this pattern are:
  • Observable - interface or abstract class defining the operations for attaching and de-attaching observers to the client. In the GOF book this class/interface is known as Subject.
  • ConcreteObservable - concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
  • Observer - interface or abstract class defining the operations to be used to notify this object.
  • ConcreteObserverA, ConcreteObserver2 - concrete Observer implementations.
The flow is simple: the main framework instantiate the ConcreteObservable object. Then it instantiate and attaches the concrete observers to it using the methods defined in the Observable interface. Each time the state of the subject it's changing it notifies all the attached Observers using the methods defined in the Observer interface. When a new Observer is added to the application, all we need to do is to instantiate it in the main framework and to add attach it to the Observable object. The classes already created will remain unchanged.


Applicability & Examples

The observer pattern is used when:
  • the change of a state in one object must be reflected in another object without keeping the objects tight coupled.
  • the framework we are writing needs to be enhanced in future with new observers with minimal changes.
Some Classical Examples:
  • Model View Controller Pattern - The observer pattern is used in the model view controller (MVC) architectural pattern. In MVC the this pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.
  • Event management - This is one of the domains where the Observer patterns is extensively used. Swing and .Net are extensively using the Observer pattern for implementing the events mechanism.


Example - News Agency

Lets' take the example of a news agency. A news agency gather news news and publish them to different subscribers. We need to create a framework for and agency to be able to inform immediately, when event occurs, its subscribers about the event. The subscribers can receive the news in different ways: Emails, SMS, ... The solution need to be extensively enough to support new types of subscribers(maybe new communication technologies will appear).
 Observer Design Pattern Newspublisher Example - UML Class Diagram
Obviously, the agency is represented by an Observable(Subject) class named NewsPublisher. This one is created as an abstract class because the agency want to create several types of Observable objects: in the beginning only for business news, but after some time sport and political new will be published. The concrete class is BusinessNewsPublisher.
The observer logic is implemented in NewsPublisher. It keeps a list of all it subscribers and it informs them about the latest news. The subscribers are represented by some observers (SMSSubscriber, EmailSubscriber). Both the observers mentioned above are inherited from the Subscriber. The subscriber is the abstract class which is known to the publisher. The publisher doesn't know about concrete observers, it knows only about their abstraction.
In the main class a publisher(Observable) is built and a few subscribers(Observers). The subscribers are subscribed to the publisher and they can be unsubscribed. In this architecture new types of subscribers can be easily added(instant messaging, ...) and new types of publishers(Weather News, Sport News, ...).

----------

Strategy


Motivation

There are common situations when classes differ only in their behavior. For this cases is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.

Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Implementation

 Strategy Implementation UML Class Diagram
Strategy - defines an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.

ConcreteStrategy - each concrete strategy implements an algorithm.

Context
  • contains a reference to a strategy object.
  • may define an interface that lets strategy accessing its data.
The Context objects contains a reference to the ConcreteStrategy that should be used. When an operation is required then the algorithm is run from the strategy object. The Context is not aware of the strategy implementation. If necessary, addition objects can be defined to pass data from context object to strategy.

The context object receives requests from the client and delegates them to the strategy object. Usually the ConcreteStartegy is created by the client and passed to the context. From this point the clients interacts only with the context.


Applicability & Examples


Example - Robots Application

Strategy Example Robot UML Class Diagram

Let's consider an application used to simulate and study robots interaction. For the beginning a simple application is created to simulate an arena where robots are interacting. We have the following classes:

IBehaviour (Strategy) - an interface that defines the behavior of a robot

Conctete Strategies: AggressiveBehaviour, DefensiveBehaviour, NormalBehaviour; each of them defines a specific behavior. In order to decide the action this class needs information that is passed from robot sensors like position, close obstacles, etc.

Robot - The robot is the context class. It keeps or gets context information such as position, close obstacles, etc, and passes necessary information to the Strategy class.

In the main section of the application the several robots are created and several different behaviors are created. Each robot has a different behavior assigned: 'Big Robot' is an aggressive one and attacks any other robot found, 'George v.2.1' is really scared and run away in the opposite direction when it encounter another robot and 'R2' is pretty calm and ignore any other robot. At some point the behaviors are changed for each robot.
public interface IBehaviour {
 public int moveCommand();
}

public class AgressiveBehaviour implements IBehaviour{
 public int moveCommand()
 {
  System.out.println("\tAgressive Behaviour: if find another robot attack it");
  return 1;
 }
}

public class DefensiveBehaviour implements IBehaviour{
 public int moveCommand()
 {
  System.out.println("\tDefensive Behaviour: if find another robot run from it");
  return -1;
 }
}

public class NormalBehaviour implements IBehaviour{
 public int moveCommand()
 {
  System.out.println("\tNormal Behaviour: if find another robot ignore it");
  return 0;
 }
}

public class Robot {
 IBehaviour behaviour;
 String name;

 public Robot(String name)
 {
  this.name = name;
 }

 public void setBehaviour(IBehaviour behaviour)
 {
  this.behaviour = behaviour;
 }

 public IBehaviour getBehaviour()
 {
  return behaviour;
 }

 public void move()
 {
  System.out.println(this.name + ": Based on current position" +
      "the behaviour object decide the next move:");
  int command = behaviour.moveCommand();
  // ... send the command to mechanisms
  System.out.println("\tThe result returned by behaviour object " +
     "is sent to the movement mechanisms " + 
     " for the robot '"  + this.name + "'");
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}


public class Main {

 public static void main(String[] args) {

  Robot r1 = new Robot("Big Robot");
  Robot r2 = new Robot("George v.2.1");
  Robot r3 = new Robot("R2");

  r1.setBehaviour(new AgressiveBehaviour());
  r2.setBehaviour(new DefensiveBehaviour());
  r3.setBehaviour(new NormalBehaviour());

  r1.move();
  r2.move();
  r3.move();

  System.out.println("\r\nNew behaviours: " +
    "\r\n\t'Big Robot' gets really scared" +
    "\r\n\t, 'George v.2.1' becomes really mad because" +
    "it's always attacked by other robots" +
    "\r\n\t and R2 keeps its calm\r\n");

  r1.setBehaviour(new DefensiveBehaviour());
  r2.setBehaviour(new AgressiveBehaviour());

  r1.move();
  r2.move();
  r3.move();
 }
}

--------------

Template Method


Motivation

If we take a look at the dictionary definition of a template we can see that a template is a preset format, used as a starting point for a particular application so that the format does not have to be recreated each time it is used.
On the same idea is the template method is based. A template method defines an algorithm in a base class using abstract operations that subclasses override to provide concrete behavior.

Intent

- Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
- Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm's structure.
Class diagram for the classic implementation of the Template Method pattern (Template Method  design pattern).

Implementation

AbstractClass - defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
- implements a template method which defines the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
ConcreteClass - implements the primitive operations to carry out subclass-specific steps of the algorithm.
When a concrete class is called the template method code will be executed from the base class while for each method used inside the template method will be called the implementation from the derived class.


Applicability & Examples

The Template Method pattern should be used:
- to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
- when refactoring is performed and common behavior is identified among classes. A abstract base class containing all the common code (in the template method) should be created to avoid code duplication.


Example - Application used by a travel agency.

Class diagram for a sample trip(travel) classes implementing the Template Method pattern(Template Method design pattern)
Lets' assume we have to develop an application for a travel agency. The travel agency is managing each trip. All the trips contain common behavior but there are several packages. For example each trip contains the basic steps:
- The tourists are transported to the holiday location by plane/train/ships,...
- Each day they are visiting something
- They are returning back home.
So we create an abstract class containing each step as an abstract method and one concrete and final method that calls all the abstracts methods. Then we create one superclass for each package:

public class Trip {
        public final void performTrip(){
                 doComingTransport();
                 doDayA();
                 doDayB();
                 doDayC();
                 doReturningTransport
        }
        public abstract void doComingTransport();
        public abstract void doDayA();
        public abstract void doDayB();
        public abstract void doDayC();
        public abstract void doReturningTransport();
}

public class PackageA extends Trip {
        public void doComingTransport() {
                 System.out.println("The turists are comming by air ...");
        }
        public void doDayA() {
                 System.out.println("The turists are visiting the aquarium ...");
        }
        public void doDayB() {
                 System.out.println("The turists are going to the beach ...");
        }
        public void doDayC() {
                 System.out.println("The turists are going to mountains ...");
        }
        public void doReturningTransport() {
                 System.out.println("The turists are going home by air ...");
        }
}
public class PackageB extends Trip {
        public void doComingTransport() {
                 System.out.println("The turists are comming by train ...");
        }
        public void doDayA() {
                 System.out.println("The turists are visiting the mountain ...");
        }
        public void doDayB() {
                 System.out.println("The turists are going to the beach ...");
        }
        public void doDayC() {
                 System.out.println("The turists are going to zoo ...");
        }
        public void doReturningTransport() {
                 System.out.println("The turists are going home by train ...");
        }
}
------------

Visitor Pattern


Motivation

Collections are data types widely used in object oriented programming. Often collections contain objects of different types and in those cases some operations have to be performed on all the collection elements without knowing the type.

A possible approach to apply a specific operation on objects of different types in a collection would be the use if blocks in conjunction with 'instanceof' for each element. This approach is not a nice one, not flexible and not object oriented at all. At this point we should think to the Open Close principle and we should remember from there that we can replace if blocks with an abstract class and each concrete class will implement its own operation.

Intent

  • Represents an operation to be performed on the elements of an object structure.
  • Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Implementation

Visitor Pattern - UML Class Diagram
The participants classes in this pattern are:
  • Visitor - This is an interface or an abstract class used to declare the visit operations for all the types of visitable classes. Usually the name of the operation is the same and the operations are differentiated by the method signature: The input object type decides which of the method is called.
  • ConcreteVisitor - For each type of visitor all the visit methods, declared in abstract visitor, must be implemented. Each Visitor will be responsible for different operations. When a new visitor is defined it has to be passed to the object structure.
  • Visitable - is an abstraction which declares the accept operation. This is the entry point which enables an object to be "visited" by the visitor object. Each object from a collection should implement this abstraction in order to be able to be visited.
  • ConcreteVisitable - Those classes implements the Visitable interface or class and defines the accept operation. The visitor object is passed to this object using the accept operation.
  • ObjectStructure - This is a class containing all the objects that can be visited. It offers a mechanism to iterate through all the elements. This structure is not necessarily a collection. In can be a complex structure, such as a composite object.


Applicability & Examples

The visitor pattern is used when:
  • Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure).
  • There are many distinct and unrelated operations needed to be performed. Visitor pattern allows us to create a separate visitor concrete class for each type of operation and to separate this operation implementation from the objects structure.
  • The object structure is not likely to be changed but is very probable to have new operations which have to be added. Since the pattern separates the visitor (representing operations, algorithms, behaviors) from the object structure it's very easy to add new visitors as long as the structure remains unchanged.


Example 1 - Customers Application.

We want to create a reporting module in our application to make statistics about a group of customers. The statistics should made very detailed so all the data related to the customer must be parsed. All the entities involved in this hierarchy must accept a visitor so the CustomerGroup, Customer, Order and Item are visitable objects.
In the example we can see the following actors:
  • IVisitor and IVisitable interfaces
  • CustomerGroup, Customer, Order and Item are all visitable classes. A CustomerGroup represents a group of customers, each Customer can have one or more orders and each order can have one ore more Items.
  • GeneralReport is a visitor class and implements the IVisitor interface.

Visitor Customers Example - UML Class Diagram

------------

Null Object Pattern


Motivation

There are some cases when a system has to use some functionality and some cases when it doesn't. Let's say we have to implement a class that should send the results to a log file or to the console. But this is just an additional option and the data is logged depending on the configuration values.

If there are cases when the client module does not have to log any data then it has to check the configuration parameter in and if block and then to call or not the Logger class. But as we know the 'if' block is not an elegant solution.

Intent

  • Provide an object as a surrogate for the lack of an object of a given type.
  • The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators.

Null Object   Pattern - UML Class Diagram - Classic Implementation, relevand for Java, C# .NET

Implementation

The participants classes in this pattern are:
  • AbstractClass - defines abstract primitive operations that concrete implementations have to define.
  • RealClass - a real implementation of the AbstractClass performing some real actions.
  • NullClass - a implementation which do nothing of the abstract class, in order to provide a non-null object to the client.
  • Client - the client gets an implementation of the abstract class and uses it. It doesn't really care if the implementation is a null object or an real object since both of them are used in the same way.


Applicability & Examples



Example: Log System

Let's say we need a logging framework in order to support the logging of an application. The framework must fulfill the following requirements:
  • The destination of the output messages should be selected from a configuration file and it can be one of the following options: Log File, Standard Console or Log Disabled.
  • Must be open for extension; new logging mechanism can be added without touching the existing code.


 (Source: Internet)

1 comment: