Jul 3, 2013

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

Adapter Pattern

Motivation

The adapter pattern is adapting between classes and objects. Like any adapter in the real world it is used to be an interface, a bridge between two objects. In real world we have adapters for power supplies, adapters for camera memory cards, and so on. Probably everyone have seen some adapters for memory cards. If you can not plug in the camera memory in your laptop you can use and adapter. You plug the camera memory in the adapter and the adapter in to laptop slot. That's it, it's really simple.
What about software development? It's the same. Can you imagine an situation when you have some class expecting some type of object and you have an object offering the same features, but exposing a different interface? Of course, you want to use both of them so you don't to implement again one of them, and you don't want to change existing classes, so why not create an adapter...

Intent

  • Convert the interface of a class into another interface clients expect.
  • Adapter lets classes work together, that could not otherwise because of incompatible interfaces.

Implementation

The figure below shows a UML class diagram for the Adapter Pattern:
Adapter  Pattern Implementation - UML Class Diagram

The classes/objects participating in adapter pattern:
  • Target - defines the domain-specific interface that Client uses.
  • Adapter - adapts the interface Adaptee to the Target interface.
  • Adaptee - defines an existing interface that needs adapting.
  • Client - collaborates with objects conforming to the Target interface.


Applicability & Examples

The visitor pattern is used when:
  • When you have a class(Target) that invokes methods defined in an interface and you have a another class(Adapter) that doesn't implement the interface but implements the operations that should be invoked from the first class through the interface. You can change none of the existing code. The adapter will implement the interface and will be the bridge between the 2 classes.
  • When you write a class (Target) for a generic use relying on some general interfaces and you have some implemented classes, not implementing the interface, that needs to be invoked by the Target class.
Adapters are encountered everywhere. From real world adapters to software adapters
  • Non Software Examples of Adapter Patterns : Power Supply Adapters, card readers and adapters, ...
  • Software Examples of Adapter Patterns: Wrappers used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.
---------

Bridge Pattern

Motivation

Sometimes an abstraction should have different implementations; consider an object that handles persistence of objects over different platforms using either relational databases or file system structures (files and folders). A simple implementation might choose to extend the object itself to implement the functionality for both file system and RDBMS. However this implementation would create a problem; Inheritance binds an implementation to the abstraction and thus it would be difficult to modify, extend, and reuse abstraction and implementation independently.

Intent

  • The intent of this pattern is to decouple abstraction from implementation so that the two can vary independently.

Implementation

The figure below shows a UML class diagram for the Bridge Pattern:
Bridge Pattern Implementation - UML Class Diagram
The participants classes in the bridge pattern are:
  • Abstraction - Abstraction defines abstraction interface.
  • AbstractionImpl - Implements the abstraction interface using a reference to an object of type Implementor.
  • Implementor - Implementor defines the interface for implementation classes. This interface does not need to correspond directly to abstraction interface and can be very different. Abstraction imp provides an implementation in terms of operations provided by Implementor interface.
  • ConcreteImplementor1, ConcreteImplementor2 - Implements the Implementor interface.

Description

An Abstraction can be implemented by an abstraction implementation, and this implementation does not depend on any concrete implementers of the Implementor interface. Extending the abstraction does not affect the Implementor. Also extending the Implementor has no effect on the Abstraction.

Applicability & Examples

The bridge pattern applies when there is a need to avoid permanent binding between an abstraction and an implementation and when the abstraction and implementation need to vary independently. Using the bridge pattern would leave the client code unchanged with no need to recompile the code.


Example - Object Persistence API Example

As discussed previously a persistence API can have many implementations depending on the presence or absence of a relational database, a file system, as well as on the underlying operating system.
Bridge Pattern Example - UML Class Diagram


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

Composite Pattern

Motivation

There are times when a program needs to manipulate a tree data structure and it is necessary to treat both Branches as well as Leaf Nodes uniformly. Consider for example a program that manipulates a file system. A file system is a tree structure that contains Branches which are Folders as well as Leaf nodes which are Files. Note that a folder object usually contains one or more file or folder objects and thus is a complex object where a file is a simple object. Note also that since files and folders have many operations and attributes in common, such as moving and copying a file or a folder, listing file or folder attributes such as file name and size, it would be easier and more convenient to treat both file and folder objects uniformly by defining a File System Resource Interface.

Intent

  • The intent of this pattern is to compose objects into tree structures to represent part-whole hierarchies.
  • Composite lets clients treat individual objects and compositions of objects uniformly.

Implementation

The figure below shows a UML class diagram for the Composite Pattern:
Composite Pattern Implementation - UML Class Diagram

  • Component - Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders.
  • Leaf - Leafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSize methods which are related to the Component interface.
  • Composite - A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components.
  • Client - The client manipulates objects in the hierarchy using the component interface.
A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn�t matter if the node is a composite or a leaf.

Applicability & Examples

The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with objects uniformly regardless of the fact that an object might be a leaf or a branch.

Example - Graphics Drawing Editor.

In graphics editors a shape can be basic or complex. An example of a simple shape is a line, where a complex shape is a rectangle which is made of four line objects. Since shapes have many operations in common such as rendering the shape to screen, and since shapes follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all shapes uniformly.
In the example we can see the following actors:
  • Shape (Component) - Shape is the abstraction for Lines, Rectangles (leafs) and and ComplexShapes (composites).
  • Line, Rectangle (Leafs) - objects that have no children. They implement services described by the Shape interface.
  • ComplexShape (Composite) - A Composite stores child Shapes in addition to implementing methods defined by the Shape interface.
  • GraphicsEditor (Client) - The GraphicsEditor manipulates Shapes in the hierarchy.
Alternative Implementation: Note that in the previous example there were times when we have avoided dealing with composite objects through the Shape interface and we have specifically dealt with them as composites (when using the method addToShape()). To avoid such situations and to further increase uniformity one can add methods to add, remove, as well as get child components to the Shape interface. The UML diagram below shows it:
Composite Pattern Alternative Implementation - UML Class Diagram

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

Decorator Pattern

Motivation

Extending an object�s functionality can be done statically (at compile time) by using inheritance however it might be necessary to extend an object�s functionality dynamically (at runtime) as an object is used.
Consider the typical example of a graphical window. To extend the functionality of the graphical window for example by adding a frame to the window, would require extending the window class to create a FramedWindow class. To create a framed window it is necessary to create an object of the FramedWindow class. However it would be impossible to start with a plain window and to extend its functionality at runtime to become a framed window.

Intent

  • The intent of this pattern is to add additional responsibilities dynamically to an object.

Implementation

The figure below shows a UML class diagram for the Decorator Pattern:
Decorator Pattern Implementation - UML Class Diagram The participants classes in the decorator pattern are:
  • Component - Interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent - Defines an object to which additional responsibilities can be added.
  • Decorator - Maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • Concrete Decorators - Concrete Decorators extend the functionality of the component by adding state or adding behavior.

Description

The decorator pattern applies when there is a need to dynamically add as well as remove responsibilities to a class, and when subclassing would be impossible due to the large number of subclasses that could result.

Applicability & Examples



Example - Extending capabilities of a Graphical Window at runtime

Decorator Pattern Example - UML Class Diagram

----------

Flyweight Pattern

Motivation

Some programs require a large number of objects that have some shared state among them. Consider for example a game of war, were there is a large number of soldier objects; a soldier object maintain the graphical representation of a soldier, soldier behavior such as motion, and firing weapons, in addition soldier�s health and location on the war terrain. Creating a large number of soldier objects is a necessity however it would incur a huge memory cost. Note that although the representation and behavior of a soldier is the same their health and location can vary greatly.

Intent

  • The intent of this pattern is to use sharing to support a large number of objects that have part of their internal state in common where the other part of state can vary.

Implementation

The figure below shows a UML class diagram for the Flyweight Pattern:
Flyweight Pattern Implementation - UML Class Diagram
  • Flyweight - Declares an interface through which flyweights can receive and act on extrinsic state.
  • ConcreteFlyweight - Implements the Flyweight interface and stores intrinsic state. A ConcreteFlyweight object must be sharable. The Concrete flyweight object must maintain state that it is intrinsic to it, and must be able to manipulate state that is extrinsic. In the war game example graphical representation is an intrinsic state, where location and health states are extrinsic. Soldier moves, the motion behavior manipulates the external state (location) to create a new location.
  • FlyweightFactory - The factory creates and manages flyweight objects. In addition the factory ensures sharing of the flyweight objects. The factory maintains a pool of different flyweight objects and returns an object from the pool if it is already created, adds one to the pool and returns it in case it is new.
    In the war example a Soldier Flyweight factory can create two types of flyweights : a Soldier flyweight, as well as a Colonel Flyweight. When the Client asks the Factory for a soldier, the factory checks to see if there is a soldier in the pool, if there is, it is returned to the client, if there is no soldier in pool, a soldier is created, added to pool, and returned to the client, the next time a client asks for a soldier, the soldier created previously is returned, no new soldier is created.
  • Client - A client maintains references to flyweights in addition to computing and maintaining extrinsic state
A client needs a flyweight object; it calls the factory to get the flyweight object. The factory checks a pool of flyweights to determine if a flyweight object of the requested type is in the pool, if there is, the reference to that object is returned. If there is no object of the required type, the factory creates a flyweight of the requested type, adds it to the pool, and returns a reference to the flyweight. The flyweight maintains intrinsic state (state that is shared among the large number of objects that we have created the flyweight for) and provides methods to manipulate external state (State that vary from object to object and is not common among the objects we have created the flyweight for).

Applicability & Examples

The flyweight pattern applies to a program using a huge number of objects that have part of their internal state in common where the other part of state can vary. The pattern is used when the larger part of the object�s state can be made extrinsic (external to that object).


Example - The war game.

The war game instantiates 5 Soldier clients, each client maintains its internal state which is extrinsic to the soldier flyweight. And Although 5 clients have been instantiated only one flyweight Soldier has been used.
Flyweight Pattern Example - UML Class Diagram 
----------

Memento Pattern

Motivation

It is sometimes necessary to capture the internal state of an object at some point and have the ability to restore the object to that state later in time. Such a case is useful in case of error or failure. Consider the case of a calculator object with an undo operation such a calculator could simply maintain a list of all previous operation that it has performed and thus would be able to restore a previous calculation it has performed. This would cause the calculator object to become larger, more complex, and heavyweight, as the calculator object would have to provide additional undo functionality and should maintain a list of all previous operations. This functionality can be moved out of the calculator class, so that an external (let's call it undo manager class) can collect the internal state of the calculator and save it. However providing the explicit access to every state variable of the calculator to the restore manager would be impractical and would violate the encapsulation principle.

Intent

  • The intent of this pattern is to capture the internal state of an object without violating encapsulation and thus providing a mean for restoring the object into initial state when needed.

Implementation

The figure below shows a UML class diagram for the Memento Pattern:
Memento Pattern Implementation - UML Class Diagram
  • Memento
    • Stores internal state of the Originator object. The state can include any number of state variables.
    • The Memento must have two interfaces, an interface to the caretaker. This interface must not allow any operations or any access to internal state stored by the memento and thus honors encapsulation. The other interface is to the originator and allows the originator to access any state variables necessary to for the originator to restore previous state.
  • Originator
    • Creates a memento object capturing the originators internal state.
    • Use the memento object to restore its previous state.
  • Caretaker
    • Responsible for keeping the memento.
    • The memento is opaque to the caretaker, and the caretaker must not operate on it.
A Caretaker would like to perform an operation on the Originator while having the possibility to rollback. The caretaker calls the createMemento() method on the originator asking the originator to pass it a memento object. At this point the originator creates a memento object saving its internal state and passes the memento to the caretaker. The caretaker maintains the memento object and performs the operation. In case of the need to undo the operation, the caretaker calls the setMemento() method on the originator passing the maintained memento object. The originator would accept the memento, using it to restore its previous state.

Applicability & Examples

The memento pattern is used when a snapshot of an object's state must be captured so that it can be restored to that state later and in situations where explicitly passing the state of the object would violate encapsulation.

Example - Simple Calculator with Undo Operation.

This simple example is a calculator that finds the result of addition of two numbers, with the additional option to undo last operation and restore previous result.
Memento Pattern Alternative Implementation - UML Class Diagram

-------

Proxy Pattern

Motivation

Sometimes we need the ability to control the access to an object. For example if we need to use only a few methods of some costly objects we'll initialize those objects when we need them entirely. Until that point we can use some light objects exposing the same interface as the heavy objects. These light objects are called proxies and they will instantiate those heavy objects when they are really need and by then we'll use some light objects instead.
This ability to control the access to an object can be required for a variety of reasons: controlling when a costly object needs to be instantiated and initialized, giving different access rights to an object, as well as providing a sophisticated means of accessing and referencing objects running in other processes, on other machines.
Consider for example an image viewer program. An image viewer program must be able to list and display high resolution photo objects that are in a folder, but how often do someone open a folder and view all the images inside. Sometimes you will be looking for a particular photo, sometimes you will only want to see an image name. The image viewer must be able to list all photo objects, but the photo objects must not be loaded into memory until they are required to be rendered.

Intent

  • The intent of this pattern is to provide a �Placeholder� for an object to control references to it.

Implementation

The figure below shows a UML class diagram for the Proxy Pattern:
Proxy Pattern Implementation - UML Class Diagram
The participants classes in the proxy pattern are:
  • Subject - Interface implemented by the RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.
  • Proxy
    • Maintains a reference that allows the Proxy to access the RealSubject.
    • Implements the same interface implemented by the RealSubject so that the Proxy can be substituted for the RealSubject.
    • Controls access to the RealSubject and may be responsible for its creation and deletion.
    • Other responsibilities depend on the kind of proxy.
  • RealSubject - the real object that the proxy represents.

Description

A client obtains a reference to a Proxy, the client then handles the proxy in the same way it handles RealSubject and thus invoking the method doSomething(). At that point the proxy can do different things prior to invoking RealSubject�s doSomething() method. The client might create a RealSubject object at that point, perform initialization, check permissions of the client to invoke the method, and then invoke the method on the object. The client can also do additional tasks after invoking the doSomething() method, such as incrementing the number of references to the object.

Applicability & Examples

The Proxy design pattern is applicable when there is a need to control access to an Object, as well as when there is a need for a sophisticated reference to an Object. Common Situations where the proxy pattern is applicable are:
  • Virtual Proxies: delaying the creation and initialization of expensive objects until needed, where the objects are created on demand (For example creating the RealSubject object only when the doSomething method is invoked).
  • Remote Proxies: providing a local representation for an object that is in a different address space. A common example is Java RMI stub objects. The stub object acts as a proxy where invoking methods on the stub would cause the stub to communicate and invoke methods on a remote object (called skeleton) found on a different machine.
  • Protection Proxies: where a proxy controls access to RealSubject methods, by giving access to some objects while denying access to others.
  • Smart References: providing a sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand.


Example - Virtual Proxy Example.

Consider an image viewer program that lists and displays high resolution photos. The program has to show a list of all photos however it does not need to display the actual photo until the user selects an image item from a list.
Proxy Pattern Virtual Proxy Example - UML Class Diagram

The code below shows the Image interface representing the Subject. The interface has a single method showImage() that the Concrete Images must implement to render an image to screen.
package proxy;

/**
 * Subject Interface
 */
public interface Image {

 public void showImage();
 
}

The code below shows the Proxy implementation, the image proxy is a virtual proxy that creates and loads the actual image object on demand, thus saving the cost of loading an image into memory until it needs to be rendered:
package proxy;

/**
 * Proxy
 */
public class ImageProxy implements Image {

 /**
  * Private Proxy data 
  */
 private String imageFilePath;
 
 /**
  * Reference to RealSubject
  */
 private Image proxifiedImage;
 
 
 public ImageProxy(String imageFilePath) {
  this.imageFilePath= imageFilePath; 
 }
 
 @Override
 public void showImage() {

  // create the Image Object only when the image is required to be shown
  
  proxifiedImage = new HighResolutionImage(imageFilePath);
  
  // now call showImage on realSubject
  proxifiedImage.showImage();
  
 }

}

The code below displays the RealSubject Implementation, which is the concrete and heavyweight implementation of the image interface. The High resolution image, loads a high resolution image from disk, and renders it to screen when showImage() is called.
package proxy;

/**
 * RealSubject
 */
public class HighResolutionImage implements Image {

 public HighResolutionImage(String imageFilePath) {
  
  loadImage(imageFilePath);
 }

 private void loadImage(String imageFilePath) {

  // load Image from disk into memory
  // this is heavy and costly operation
 }

 @Override
 public void showImage() {

  // Actual Image rendering logic

 }

}

The code below illustrates a sample image viewer program; the program simply loads three images, and renders only one image, once using the proxy pattern, and another time directly. Note that when using the proxy pattern, although three images have been loaded, the High resolution image is not loaded into memory until it needs to be rendered, while in the part not using the proxy, the three images are loaded into memory although one of them is actually rendered.
package proxy;

/**
 * Image Viewer program
 */
public class ImageViewer {

 
 public static void main(String[] args) {
  
 // assuming that the user selects a folder that has 3 images 
 //create the 3 images  
 Image highResolutionImage1 = new ImageProxy("sample/veryHighResPhoto1.jpeg");
 Image highResolutionImage2 = new ImageProxy("sample/veryHighResPhoto2.jpeg");
 Image highResolutionImage3 = new ImageProxy("sample/veryHighResPhoto3.jpeg");
 
 // assume that the user clicks on Image one item in a list
 // this would cause the program to call showImage() for that image only
 // note that in this case only image one was loaded into memory
 highResolutionImage1.showImage();
 
 // consider using the high resolution image object directly
 Image highResolutionImageNoProxy1 = new HighResolutionImage("sample/veryHighResPhoto1.jpeg");
 Image highResolutionImageNoProxy2 = new HighResolutionImage("sample/veryHighResPhoto2.jpeg");
 Image highResolutionImageBoProxy3 = new HighResolutionImage("sample/veryHighResPhoto3.jpeg");
 
 
 // assume that the user selects image two item from images list
 highResolutionImageNoProxy2.showImage();
 
 // note that in this case all images have been loaded into memory 
 // and not all have been actually displayed
 // this is a waste of memory resources
 
 }
  
}


(Source: Internet)

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)

Best tutorial - Java Design patterns (Part 2) - Creational Design Patterns

Singleton Pattern

 Motivation

Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.

Implementation

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.
Singleton Implementation - UML Class Diagram
The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.
class Singleton
{
 private static Singleton instance;
 private Singleton()
 {
  ...
 }

 public static synchronized Singleton getInstance()
 {
  if (instance == null)
   instance = new Singleton();

  return instance;
 }
 ...
 public void doSomething()
 {
  ... 
 }
}
You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.
The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:
Singleton.getInstance().doSomething();

Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

 ----------

Factory Pattern

Motivation

The Factory Design Pattern is probably the most used design pattern in modern programming languages like Java and C#. It comes in different variants and implementations. If you are searching for it, most likely, you'll find references about the GoF patterns: Factory Method and Abstract Factory.

In this article we'll describe a flavor of factory pattern commonly used nowdays. You can also check the original Factory Method pattern which is very similar.

Intent

  • creates objects without exposing the instantiation logic to the client.
  • refers to the newly created object through a common interface

Implementation

Factory Implementation - UML Class Diagram
The implementation is really simple
  • The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
  • The factory instantiates a new concrete product and then returns to the client the newly created product(casted to abstract product class).
  • The client uses the products as abstract products without being aware about their concrete implementation.

---------

Abstract Factory

Motivation

Modularization is a big issue in today's programming. Programmers all over the world are trying to avoid the idea of adding code to existing classes in order to make them support encapsulating more general information. Take the case of a information manager which manages phone number. Phone numbers have a particular rule on which they get generated depending on areas and countries. If at some point the application should be changed in order to support adding numbers form a new country, the code of the application would have to be changed and it would become more and more complicated.
In order to prevent it, the Abstract Factory design pattern is used. Using this pattern a framework is defined, which produces objects that follow a general pattern and at runtime this factory is paired with any concrete factory to produce objects that follow the pattern of a certain country. In other words, the Abstract Factory is a super-factory which creates other factories (Factory of factories).

Intent

  • Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes.

Implementation

The pattern basically works as shown below, in the UML diagram:
Abstract Factory Implementation - UML Class Diagram

The classes that participate to the Abstract Factory pattern are:
  • AbstractFactory - declares a interface for operations that create abstract products.
  • ConcreteFactory - implements operations to create concrete products.
  • AbstractProduct - declares an interface for a type of product objects.
  • Product - defines a product to be created by the corresponding ConcreteFactory; it implements the AbstractProduct interface.
  • Client - uses the interfaces declared by the AbstractFactory and AbstractProduct classes.
The AbstractFactory class is the one that determines the actual type of the concrete object and creates it, but it returns an abstract pointer to the concrete object just created. This determines the behavior of the client that asks the factory to create an object of a certain abstract type and to return the abstract pointer to it, keeping the client from knowing anything about the actual creation of the object.
The fact that the factory returns an abstract pointer to the created object means that the client doesn't have knowledge of the object's type. This implies that there is no need for including any class declarations relating to the concrete type, the client dealing at all times with the abstract type. The objects of the concrete type, created by the factory, are accessed by the client only through the abstract interface.
The second implication of this way of creating objects is that when the adding new concrete types is needed, all we have to do is modify the client code and make it use a different factory, which is far easier than instantiating a new type, which requires changing the code wherever a new object is created.
The classic implementation for the Abstract Factory pattern is the following:
abstract class AbstractProductA{
 public abstract void operationA1();
 public abstract void operationA2();
}

class ProductA1 extends AbstractProductA{
 ProductA1(String arg){
  System.out.println("Hello "+arg);
 } // Implement the code here
 public void operationA1() { };
 public void operationA2() { };
}

class ProductA2 extends AbstractProductA{
 ProductA2(String arg){
  System.out.println("Hello "+arg);
 } // Implement the code here
 public void operationA1() { };
 public void operationA2() { };
}

abstract class AbstractProductB{
 //public abstract void operationB1();
 //public abstract void operationB2();
}

class ProductB1 extends AbstractProductB{
 ProductB1(String arg){
  System.out.println("Hello "+arg);
 } // Implement the code here
}

class ProductB2 extends AbstractProductB{
 ProductB2(String arg){
  System.out.println("Hello "+arg);
 } // Implement the code here
}

abstract class AbstractFactory{
 abstract AbstractProductA createProductA();
 abstract AbstractProductB createProductB();
}

class ConcreteFactory1 extends AbstractFactory{
 AbstractProductA createProductA(){
  return new ProductA1("ProductA1");
 }
 AbstractProductB createProductB(){
  return new ProductB1("ProductB1");
 }
}

class ConcreteFactory2 extends AbstractFactory{
 AbstractProductA createProductA(){
  return new ProductA2("ProductA2");
 }
 AbstractProductB createProductB(){
  return new ProductB2("ProductB2");
 }
}

//Factory creator - an indirect way of instantiating the factories
class FactoryMaker{
 private static AbstractFactory pf=null;
 static AbstractFactory getFactory(String choice){
  if(choice.equals("a")){
   pf=new ConcreteFactory1();
  }else if(choice.equals("b")){
    pf=new ConcreteFactory2();
   } return pf;
 }
}

// Client
public class Client{
 public static void main(String args[]){
  AbstractFactory pf=FactoryMaker.getFactory("a");
  AbstractProductA product=pf.createProductA();
  //more function calls on product
 }
}

Applicability & Examples

We should use the Abstract Factory design pattern when:
  • the system needs to be independent from the way the products it works with are created.
  • the system is or should be configured to work with multiple families of products.
  • a family of products is designed to work only all together.
  • the creation of a library of products is needed, for which is relevant only the interface, not the implementation, too.

Phone Number Example

The example at the beginning of the article can be extended to addresses, too. The AbstractFactory class will contain methods for creating a new entry in the information manager for a phone number and for an address, methods that produce the abstract products Address and PhoneNumber, which belong to AbstractProduct classes. The AbstractProduct classes will define methods that these products support: for the address get and set methods for the street, city, region and postal code members and for the phone number get and set methods for the number.
The ConcreteFactory and ConcreteProduct classes will implement the interfaces defined above and will appear in our example in the form of the USAddressFactory class and the USAddress and USPhoneNumber classes. For each new country that needs to be added to the application, a new set of concrete-type classes will be added. This way we can have the EnglandAddressFactory and the EnglandAddress and EnglandPhoneNumber that are files for English address information.

Pizza Factory Example

Another example, this time more simple and easier to understand, is the one of a pizza factory, which defines method names and returns types to make different kinds of pizza. The abstract factory can be named AbstractPizzaFactory, RomeConcretePizzaFactory and MilanConcretePizzaFactory being two extensions of the abstract class. The abstract factory will define types of toppings for pizza, like pepperoni, sausage or anchovy, and the concrete factories will implement only a set of the toppings, which are specific for the area and even if one topping is implemented in both concrete factories, the resulting pizzas will be different subclasses, each for the area it was implemented in.

----------

Builder Pattern



Motivation

The more complex an application is the complexity of classes and objects used increases. Complex objects are made of parts produced by other objects that need special care when being built. An application might need a mechanism for building complex objects that is independent from the ones that make up the object. If this is the problem you are being confronted with, you might want to try using the Builder (or Adaptive Builder) design pattern.
This pattern allows a client object to construct a complex object by specifying only its type and content, being shielded from the details related to the object�s representation. This way the construction process can be used to create different representations. The logic of this process is isolated form the actual steps used in creating the complex object, so the process can be used again to create a different object form the same set of simple objects as the first one.

Intent

  • Defines an instance for creating an object but letting subclasses decide which class to instantiate
  • Refers to the newly created object through a common interface

Implementation

The Builder design pattern uses the Factory Builder pattern to decide which concrete class to initiate in order to build the desired type of object, as we will see below in the UML diagram:
Builder Pattern - UML Class Diagram

The participants classes in this pattern are:
  • The Builder class specifies an abstract interface for creating parts of a Product object.
  • The ConcreteBuilder constructs and puts together parts of the product by implementing the Builder interface. It defines and keeps track of the representation it creates and provides an interface for saving the product.
  • The Director class constructs the complex object using the Builder interface.
  • The Product represents the complex object that is being built.
The client, that may be either another object or the actual client that calls the main() method of the application, initiates the Builder and Director class. The Builder represents the complex object that needs to be built in terms of simpler objects and types. The constructor in the Director class receives a Builder object as a parameter from the Client and is responsible for calling the appropriate methods of the Builder class. In order to provide the Client with an interface for all concrete Builders, the Builder class should be an abstract one. This way you can add new types of complex objects by only defining the structure and reusing the logic for the actual construction process. The Client is the only one that needs to know about the new types, the Director needing to know which methods of the Builder to call.
The following example discusses the case of a text converting application:
Builder Pattern Example - UML Class Diagram The Client needs to convert a document from RTF format to ASCII format. There for, it calls the method createASCIIText that takes as a parameter the document that will be converted. This method calls the concrete builder, ASCIIConverter, that extends the Builder, TextConverter, and overrides its two methods for converting characters and paragraphs, and also the Director, RTFReader, that parses the document and calls the builder�s methods depending on the type of token encountered. The product, the ASCIIText, is built step by step, by appending converted characters.
//Abstract Builder
class abstract class TextConverter{
 abstract void convertCharacter(char c);
 abstract void convertParagraph();
}

// Product
class ASCIIText{
 public void append(char c){ //Implement the code here }
}

//Concrete Builder
class ASCIIConverter extends TextConverter{
 ASCIIText asciiTextObj;//resulting product

 /*converts a character to target representation and appends to the resulting*/
 object void convertCharacter(char c){
  char asciiChar = new Character(c).charValue();
   //gets the ascii character
  asciiTextObj.append(asciiChar);
 }
 void convertParagraph(){}
 ASCIIText getResult(){
  return asciiTextObj;
 }
}

//This class abstracts the document object
class Document{
 static int value;
 char token;
 public char getNextToken(){
  //Get the next token
  return token;
 }
}

//Director
class RTFReader{
 private static final char EOF='0'; //Delimitor for End of File
 final char CHAR='c';
 final char PARA='p';
 char t;
 TextConverter builder;
 RTFReader(TextConverter obj){
  builder=obj;
 }
 void parseRTF(Document doc){
  while ((t=doc.getNextToken())!= EOF){
   switch (t){
    case CHAR: builder.convertCharacter(t);
    case PARA: builder.convertParagraph();
   }
  }
 }
}

//Client
public class Client{
 void createASCIIText(Document doc){
  ASCIIConverter asciiBuilder = new ASCIIConverter();
  RTFReader rtfReader = new RTFReader(asciiBuilder);
  rtfReader.parseRTF(doc);
  ASCIIText asciiText = asciiBuilder.getResult();
 }
 public static void main(String args[]){
  Client client=new Client();
  Document doc=new Document();
  client.createASCIIText(doc);
  system.out.println("This is an example of Builder Pattern");
 }
}


Applicability & Examples

Builder Pattern is used when:
  • the creation algorithm of a complex object is independent from the parts that actually compose the object
  • the system needs to allow different representations for the objects that are being built

Example 1 - Vehicle Manufacturer.

Let us take the case of a vehicle manufacturer that, from a set of parts, can build a car, a bicycle, a motorcycle or a scooter. In this case the Builder will become the VehicleBuilder. It specifies the interface for building any of the vehicles in the list above, using the same set of parts and a different set of rules for every type of type of vehicle. The ConcreteBuilders will be the builders attached to each of the objects that are being under construction. The Product is of course the vehicle that is being constructed and the Director is the manufacturer and its shop.

Example 1 - Students Exams.

If we have an application that can be used by the students of a University to provide them with the list of their grades for their exams, this application needs to run in different ways depending on the user that is using it, user that has to log in. This means that, for example, the admin needs to have some buttons enabled, buttons that needs to be disabled for the student, the common user. The Builder provides the interface for building form depending on the login information. The ConcreteBuilders are the specific forms for each type of user. The Product is the final form that the application will use in the given case and the Director is the application that, based on the login information, needs a specific form.

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

Prototype Pattern


Motivation

Today’s programming is all about costs. Saving is a big issue when it comes to using computer resources, so programmers are doing their best to find ways of improving the performance When we talk about object creation we can find a better way to have new objects: cloning. To this idea one particular design pattern is related: rather than creation it uses cloning. If the cost of creating a new object is large and creation is resource intensive, we clone the object.
The Prototype design pattern is the one in question. It allows an object to create customized objects without knowing their class or any details of how to create them. Up to this point it sounds a lot like the Factory Method pattern, the difference being the fact that for the Factory the palette of prototypical objects never contains more than one object.

Intent

  • specifying the kind of objects to create using a prototypical instance
  • creating new objects by copying this prototype
    • Implementation

      The pattern uses abstract classes, as we will see below and only three types of classes making its implementation rather easy.
      Prototype Implementation - UML Class DiagramThe classes participating to the Prototype Pattern are:

      • Client - creates a new object by asking a prototype to clone itself.
      • Prototype - declares an interface for cloning itself.
      • ConcretePrototype - implements the operation for cloning itself.
      • The process of cloning starts with an initialized and instantiated class. The Client asks for a new object of that type and sends the request to the Prototype class. A ConcretePrototype, depending of the type of object is needed, will handle the cloning through the Clone() method, making a new instance of itself.
        Here is a sample code for the Prototype pattern:
        public interface Prototype {
         public abstract Object clone ( );
        }
        
         
        
        public class ConcretePrototype implements Prototype {
         public Object clone() {
          return super.clone();
         }
        }
        
        public class Client {
        
         public static void main( String arg[] ) 
         {
          ConcretePrototype obj1= new ConcretePrototype ();
          ConcretePrototype obj2 = ConcretePrototype)obj1.clone();
         }
        
        }
        
        This example is rather trivial, but the real use of the pattern comes when we don’t know what we’re actually cloning. For example if we need the newly created object to be stored in a hashtable we can use it like this:
        // Violation of Likov's Substitution Principle
        class Rectangle
        {
         protected int m_width;
         protected int m_height;
        
         public void setWidth(int width){
          m_width = width;
         }
        
         public void setHeight(int height){
          m_height = height;
         }
        
        
         public int getWidth(){
          return m_width;
         }
        
         public int getHeight(){
          return m_height;
         }
        
         public int getArea(){
          return m_width * m_height;
         } 
        }
        
        class Square extends Rectangle 
        {
         public void setWidth(int width){
          m_width = width;
          m_height = width;
         }
        
         public void setHeight(int height){
          m_width = height;
          m_height = height;
         }
        
        }
        
        class LspTest
        {
         private static Rectangle getNewRectangle()
         {
          // it can be an object returned by some factory ... 
          return new Square();
         }
        
         public static void main (String args[])
         {
          Rectangle r = LspTest.getNewRectangle();
                
          r.setWidth(5);
          r.setHeight(10);
          // user knows that r it's a rectangle.
          // It assumes that he's able to set the width and height as for the base class
        
          System.out.println(r.getArea());
          // now he's surprised to see that the area is 100 instead of 50.
         }
        }
        

        Applicability & Examples

        Use Prototype Pattern when a system should be independent of how its products are created, composed, and represented, and:
        • Classes to be instantiated are specified at run-time
        • Avoiding the creation of a factory hierarchy is needed
        • It is more convenient to copy an existing instance than to create a new one.

        Example 1

        In building stages for a game that uses a maze and different visual objects that the character encounters it is needed a quick method of generating the haze map using the same objects: wall, door, passage, room... The Prototype pattern is useful in this case because instead of hard coding (using new operation) the room, door, passage and wall objects that get instantiated, CreateMaze method will be parameterized by various prototypical room, door, wall and passage objects, so the composition of the map can be easily changed by replacing the prototypical objects with different ones.
        The Client is the CreateMaze method and the ConcretePrototype classes will be the ones creating copies for different objects.

        Example 2:

        Suppose we are doing a sales analysis on a set of data from a database. Normally, we would copy the information from the database, encapsulate it into an object and do the analysis. But if another analysis is needed on the same set of data, reading the database again and creating a new object is not the best idea. If we are using the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis.
        The Client is here one of the methods that process an object that encapsulates information from the database. The ConcretePrototype classes will be classes that, from the object created after extracting data from the database, will copy it into objects used for analysis.

 -----------

Object Pool

Motivation

Performance can be sometimes the key issue during the software development and the object creation(class instantiation) is a costly step. While the Prototype pattern helps in improving the performance by cloning the objects, the Object Pool pattern offer a mechanism to reuse objects that are expensive to create.

Clients of an object pull "feel" like they are owners of a service although the service is shared among many other clients.

Intent

-reuse and share objects that are expensive to create.


Implementation

Objectpool Implementation - UML Class Schema

Implementation involves the following objects:
Reusable - Wraps the limited resource, will be shared by several clients for a limited amount of time.
Client - uses an instance of type Reusable.
ReusablePool - manage the reusable objects for use by Clients, creating and managing a pool of objects.

When a client asks for a Reusable object, the pool performs the following actions:
-    Search for an available Reusable object and if it was found it will be returned to the client.
-    If no Reusable object was found then it tries to create a new one. If this actions succeds the new Reusable object will be returned to the client.
-    If the pool was unable to create a new Reusable, the pool will wait until a reusable object will be released.

The Client is responsible to request the Reusable object as well to release it to the pool. If this action will not be performed the Reusable object will be lost, being considered unavailable by the ResourcePool.

The clients are not aware that they are sharing the Reusable object. From the client poinf of view they are the owners of a new object which comes from the Resource pool in the same way that it comes from a factory or another creational design pattern. The only difference is that the Client should mark the Reusable object as available, after it finishes to use it. It's not about releasing the objects; for example if we work with databases, when a connection is closed it's not necesarely distroyed, it means that it can be reused by another client.

Why to use it?

Basically, we'll use an object pool whenever there are several clients who needs the same stateless resource which is expensive to create.

Applicability & Examples


Lets' take the example of the database connections. It's obviosly that opening too many connections might affect the performance for several reasons:
Creating a connection is an expensive operation.
When there are too many connections opened it takes longer to create a new one and the database server will become overloaded.

Here the object pool comes in to picture to manage the connections and provide a way to reuse and share them. It can also limit the maximum number of objects that can be created.
Objectpool Example Database Connection - UML Class Schema


This pattern provide the following mechaninsm:

Connection - represent the object which is instantiated by the client. From the client perspective this object is instantiated and it handles the database operations and it is the only object visible to the client. The client is not aware that it uses  some shared connections. Internally this class does not contain any code for connecting to the database and calls ConnectionPool.aquireImpl to get a ConnectionImpl object and then delegates the request to ConnectionImpl.

ConnectionImpl is the object which implements the database operations which are exposed by Connection for the client.

ConnectionPool is the main actor to manage the connections to the database. It keeps a list of ConnectionImpl objects and instantiates new objects if this is required.

When the client needs to query the database it instantiate a new Connection object specifing the database name and the call the query method which returns a set of records. From the client point of view this is all.

When the Connection.Query methd is called it asks for a ConnectionImpl object from the ConnectionPool. The ConnectionPool tries to find and return an unused object and if it doesn't find it creates one. At this point the maximum number of connections can be limited and if it was reached the pool cand wait until one will be available or return null. In the query method the request is delegated to the ConnectionImpl object returned by the object pool. Since the request is just delegated it's recomended to have the same method signature in Connection and ConnectionImpl.

(Source: Internet)