Tuesday 13 October 2015

Flyweight Pattern

Description

Flyweight pattern is one of the fundamental design patterns described in the volume “Design Patterns: elements of reusable object-oriented software”.
It falls in the category of structural patterns.


Purpose

Suppose that, in your app, you have to create and use many objects, and this process requires a lot of memory and/or computational resources. The purpose is to reduce the proliferation of objects as much as possible.Solution. In a class we can identify two different states:

  • internal state: internal state corresponds to the features of the object that are constant, regardless of the context in which it is used; the internal state can therefore be shared (there is no need to create different objects with the same internal state: we can re-use the already existing ones);
  • external state: external state contains the features of the object that depend on the context in which the object is created and used.
Flyweight pattern helps us to reduce the proliferation of unnecessary objects within our apps, reusing the existing objects if possible.

Implementation

In the following example we create 20 circles of different colors (5 different colors) with random location and size; using the Flyweight pattern we can create only 5 objects at most, corresponding to the 5 different colors (the color represents here the internal state of the object).

Flyweight
public interface Shape {
   void draw(int x, int y, int size);
}
This interface represents a simple geometric shape with a draw method to draw itself. The draw method takes some parameters (x, y, size) corresponding to the external state of the object (parameters set “on the fly” by the client when needed).
When defining the Flyweight interface you therefore have to find out the parameters corresponding to the external state of the object: in our simplified example the location and size of each shape.


ConcreteFlyweight
public class Circle implements Shape {
   private String color;

   public Circle(String color){
      this.color = color;               
   }


   @Override
   public void draw(int x, int y, int size) {
      System.out.println("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + size);
   }
}
Circle implements Shape interface and represents a specific geometric shape: a circle. Each circle has a color (set with the constructor) and implements the draw method taking x, y and size as parameters.
Notice that Circle has an instance variable, color, which is the internal state of the object (the part of the object that can be shared). 

The external state, depending on the context (x, y and size), is set by the client “on the fly” when the circle must be drawn and passed as a parameter to the draw method.
When defining the ConcreteFlyweight you therefore have to identify the parameters corresponding to the internal state of the object; these parameters are stored inside the object itself so that they can be shared.


FlyweightFactory
public class ShapeFactory {
   private static final HashMap circleMap = new HashMap();

   public static Shape getCircle(String color) {
      Circle circle = (Circle)circleMap.get(color);

      if(circle == null) {
         circle = new Circle(color);
         circleMap.put(color, circle);
         System.out.println("Creating circle of color : " + color);
      }
      return circle;
   }
}
ShapeFactory is a factory class creating Circle objects requested by the clients through its getCircle(String color) method.
This class keeps an internal HashMap of Circle objects, where the key is the color of the circle.
The getCircle(String color) method tries to retrieve an already existing Circle from the HashMap with the requested color. If a circle of the specified color already exists in the HashMap, getCircle simply returns it (it is not created anew); otherwise a new Circle object is created, put in the HashMap and returned to the client.
The discriminating element for deciding whether to create a new circle or not is the color, that is the internal state of the object.

Internal state of the object. Parameters that don’t vary with the context in which the object is used (in our example, the color). These parameters can be shared: there is no need to create a new object if the internal state stays the same.
External state of the object. Parameters that vary with the context in which the object is used (in our example, the location and size of each circle). These parameters are set by the client “on the fly” before invoking the required method (in our example, the draw method).


Client
public class FlyweightPatternDemo {
   private static final String colors[] = { "Red", "Green", "Blue", "White", "Black" };
   public static void main(String[] args) {

      for(int i=0; i < 20; ++i) {
         Circle circle = (Circle)ShapeFactory.getCircle(getRandomColor());
         circle.draw(getRandomX(),getRandomY(),100);
      }
   }
   private static String getRandomColor() {
      return colors[(int)(Math.random()*colors.length)];
   }
   private static int getRandomX() {
      return (int)(Math.random()*100 );
   }
   private static int getRandomY() {
      return (int)(Math.random()*100);
   }
}
In our example the client draws 20 circles with different location (x, y) and size, randomly chosen. Notice, however, that we don’t create 20 different objects but 5 at most! Circles of the same color are infact retrieved from the HashMap; the external state (x, y and size) is simply set by the client before invoking the draw method.

The discriminating element for deciding whether to create a new circle or not is the color: if the color varies a new object must be created; if the location and size vary we can re-use a circle of the same color and set these parameters by invoking the draw method.
The client doesn’t create the objects directly, but uses the factory class ShapeFactory, which is responsible for creating a new object or retrieving an already existing one.
Notice that the external state of the object (x, y and size) is not stored inside the object itself, but managed and set by the client.


Structure

UML Diagram
Notice the UnsharedConcreteFlyweight class. UnsharedConcreteFlyweight is a class whose state must not be shared (unlike the ConcreteFlyweight); at the same time UnsharedConcreteFlyweight uses the same interface of the Flyweight (in our example, a draw method with x, y and size as parameters).
Consider as an example a text editor software:
  • ConcreteFlyweight: in a text editor software the ConcreteFlyweight is a single Character, whose internal state must be shared (for example the letter represented by that charcter, ‘a’, ‘r’, ‘d’, etc.);
  • UnsharedConcreteFlyweight: a Row is a good example of an UnsharedConcreteFlyweight. Each row must be drawn according to a specific external state (size, font, etc.): it therefore implements the Flyweight interface. At the same time there is not an internal state that can be shared (each row is different from each other). UnsharedConcreteFlyweight usually have Flyweight objects as children: a Row is composed by different Characters (that are Flyweight objects).


Insights


Applications

Web browsers generally use this pattern to display images in a web page. Suppose that the same image must be displayed in the same page in different locations and sizes. The Flyweight pattern can be used here to avoid donwloading the same image more times from the web (internal state: the image to display; external state: location and size).

War game. An object of type "soldier" must be created many times because an army is composed of different soldiers. However some features are common (graphic representation, movements, etc.), while others vary depending on the context (location, health, etc.). The Flyweight pattern can be applied here to avoid the proliferation on unnecesary objects.

Text editor. In a text editor app we could use an object, let's call it Character, to represent each character in the document. Each character has some properties, like font, size, the character displayed, etc. A document contains a lot of characters, so this approach causes un unnecesary proliferation of objects. To avoid this we could apply the Flyweight pattern as follows:
  • internal state: the internal state is the character displayed ('a', 'b', 'c', etc.). For example, if the document contains several letters 'a' we don't have to create an object for each one; instead we can re-use the same object as previously described;
  • external state: the external state could be the font, the size, the location of each character.

State and Strategy pattern
State and Strategy objects are generally implemented as Flyweights.

Singleton pattern
In our example of the Flyweight pattern ConcreteFlyweights are created using a factory class. For each type of shape, that is a shape with a given color, only one instance is created: the same instance is re-used when necessary.
This is an example of application of the Singleton pattern.

Thursday 1 October 2015

GoF: Observer Pattern (aka Publish-Subscribe)

Description

The Observer Pattern is one the fundamental design patterns described by the Gang Of Four (GoF) in the volume “Design patterns – Elements of reusable object-oriented software”.
It is a behavioural pattern used when there is a “one to many” dependency between different objects: when the observed object (called Subject in the pattern) changes its state, all objects depending on it (called Observers) must be notified and updated.
This kind of interaction is also known as publish-subscribe.


UML diagram

Implementation

The code of the following example can be found here: Design Patterns in Java Github Repository.

Subject


public class Subject {
 
   private List observers = new ArrayList();
   private int state;

   public int getState() {
      return state;
   }

   public void setState(int state) {
       this.state = state;
       notifyAllObservers();
   }
 
   public void attach(Observer observer){
      observers.add(observer);  
   }

   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   }  
}

Subject is the object from which other objects depend (Observers). The class Subject keeps an internal list of Observers (see below) that can be added with the public method “attach(Observer observer)” (the class could also implement a “detach” method for removing Observers that are not used anymore).
The variable “state” represents the internal state of this object (in our simplified example it’s an integer), with public setter and getter methods.
When the state of the Subject varies, through the setState method, we have to iterate over the list of Observers and notify the change to each of them. The notification is sent to all attached Observers: it’s up to the Observer to handle or ignore the notification.
As you can see from the example above it’s very important that notifyAllObservers() is called only after the state of the Subject is updated, and not before (the Subject state must be self-consistent), because all Observers will be updated as a result of the notification. This is especially true if you need to subclass the Subject class. A possible solution is to define a template method with abstract operations that the subclasses can override, and call notifyAllObservers() as the last instruction of the method.
Notice that the class Subject keeps strong references to the attached Observers. This can cause memory leaks if some Observers are not used anymore: to fix this problem you can create a Subject class keeping weak references to the Observers, instead of strong ones.

Abstract Observer

public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}

Observer is an abstract class that must be extended. It keeps a reference to the Subject (to be able to be connected to it through the “attach” method and to get/set its state through the public setter/getter methods); it also exposes an abstract “update” method that gets invoked when the internal state of the Subject varies (this is the way the Subject communicates its changes to the Observers).

Concrete Observer

public class BinaryObserver extends Observer{
   private Subject subject;

   public BinaryObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
      System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) ); 
   }
}

There are two things to notice here: 

  1. the ConcreteObserver “BinaryObserver” (which prints the number representing the state of the Subject in binary notation) keeps a reference to the Subject: this reference is used to connect this ConcreteObserver to the Subject (“attach” method of the Subject) and to retrieve the Subject’s state through the “getState” method; 
  2. the class exposes an “update” method used to receive the notification sent by the Subject when its state varies.
The ConcreteObserver can also directly edit the state of the Subject via the “setState” method. In this case the ConcreteObserver that made the change gets also notified by the Subject (the method “nofityAllObservers” iterates over all attached Observers) and, after receiving the notification, it may possibly change its internal state.

public class OctalObserver extends Observer{
   private Subject subject;

   public OctalObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
     System.out.println( "Octal String: " + Integer.toOctalString( subject.getState() ) ); 
   }
}


This is another ConcreteObserver, printing the variable “state” of the Subject in octal notation.

Client

public class ObserverPatternDemo {
   public static void main(String[] args) {
      Subject subject = new Subject();

      new OctalObserver(subject);
      new BinaryObserver(subject);

      System.out.println("First state change: 15"); 
      subject.setState(15);
      System.out.println("Second state change: 10"); 
      subject.setState(10);
   }
}

 
Sequence

Insights

Advantages

The Observer pattern enables you to decouple the Subject and the Observers, making them reusable and modifiable independently; it also enables you to add or remove Observers according to your specific needs. Infact the Subject only knows to have some Observers attached to it and which method it has to invoke to notify its state changes (interface for notifications), but it doesn’t know more: what kind of classes they are, what they do, etc. (the coupling is abstract and minimal). If the Observers were tightly coupled to the Subject this would not be possible.
Being weakly coupled, the Subject and the Observers could belong to different layers of abstraction in a system: for example the Subject could lie on a lower level and the Observers in a higher level, thus preserving the layering of the system.


Observers depending on different Subjects

A very easy way to handle this situation consists of passing the Subject itself as a parameter in the “update” method, thus allowing the Observer to understand from which Subject the notification is coming.
If we have different interdependent Subjects and an Observer attached to them, the Observer pattern, as previously described, could be inefficient, because the Observer could receive multiple sequential notifications from the different Subjects as their states change. A better solution would be to have a single notification issued when all Subjects have changed. Solution: ChangeManager.

Notify called from the Client

With the standard Observer pattern, where the Subject invokes “update” on each Observer to notify its state changes (see the method “setState”), inefficiencies may arise when there are multiple sequential modifications on the Subject: infact each modification is notified to each Observer separetely.
In a different and better implementation the Client changes the Subject’s state and is responsible for notifying all Observer only after the different sequential modifications have been made. However if the Client forgets to issue the notifications errors may arise.

Update” method with or without parameters (push or pull model)


  • Without parameters (see the example above): the Subject simply informs all Observers that a change has occurred, but it’s the Observer’s responsibility to understand exactly what happened (pull method); this implementation decouples Subject and Observers making them easily reusable, but the notification mechanism may become inefficient.
  • With parameters: the Subject gives the Observers detailed information about the change that has occurred (push method): the notification management is more efficient, but Subject and Observers become more tightly coupled and therefore less easily reusable.

Specifying modifications of interest

Let’s suppose that an Observer is interested only in changes of the Subject of some kind, and not all. A very easy solution is to specify in the “attach” method of the Subject the type of modification of interest:
public void attach(Observer observer, Interests interest), where interest is the type of modification of interest
We also have to change the “update” method of the AbstractObserver to specify what kind of modification occurred:
public abstract voi update(Observer observer, Interests interest)

Applications

The Observer pattern is often used in the MVC – Model View Controller models and in almost all user interface toolkits. The Model (the data) is the Subject, the View (the UI) is the Observer: when data changes the UI must be updated accordingly. This way data and presentations can be reused independently.
Consider an Excel spreadsheet with some data and a pie chart and a bar chart. When data changes the pie chart and bar chart must be updated (the charts play here the role of the Observers while the data in the spreadsheet is the Subject).

Friday 25 September 2015

GoF: Singleton Pattern

Description

The Singleton Pattern is one the fundamental design patterns described by the Gang Of Four (GoF) in the volume “Design patterns – Elements of reusable object-oriented software”.

It is a creational pattern whose purpose is to make sure that of a particular class one instance, and only one instance, can be created, offering a global access point to that instance to all clients requesting it.




Simple implementation (no thread-safe)

public class Singleton {
    private static Singleton instance = null;
 
    // The constructor is private: the creation of instances must be controlled.
    // private Singleton () {}
 
    // This method is used to obtain the unique instance of this class, creating it 
    // if necessary.
    public static Singleton getMySingleton () {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Notice that the constructor of this class is private, because the creation of instances must be controlled, making sure that only one instance is created. Instances of the Singleton class cannot be created outside this class.
To obtain an instance of the Singleton class we use the method getMySingleton(). The first time this method is invoked a new instance of the class is created (instance == null); subsequently (instance != null) the same instance is returned, making sure that only one instance of this class is created and returning it to all clients requesting it.

Thread-safe implementation: synchronized

public class MySingleton {
    // volatile makes sure that changes are immediately visible to all threads.
    private volatile static Singleton instance = null;
 
    // The constructor is private: the creation of instances must be controlled.
    private MySingleton() {}
 
    // This method is used to obtain the unique instance of this class, in a 
    // thread-safe manner, creating it if necessary.
    public static Singleton getMySingleton() {
        if (instance == null) {
            // Only this part of the code must be synchronized, because the 
            // variable “instance” is of type volatile.
            synchronized (MySingleton.class){
              // I’m not sure to be the first thread to access this method
              if (instance == null)
                 instance = new Singleton();
            }
        }
        return instance;
    }
}
There are two main things to notice here:
  1. the synchronization is placed after checking that instance == null (first creation of the object): for subsequent accesses there is no need to do this, because the same instance previously created is simply returned to all clients requesting it (in this case there is no need of synchronization).
  2. after the synchronization we have to check again that instance == null. To understand this imagine that two different threads (thread 1 and thread 2) enter this method for the first time (instance == null). The first thread that enters the synchronized block (thread 1) creates the unique instance of this class and returns it. Then the second thread (thread 2) enters the same synchronized block, but this time the unique instance of the class has already been created (instance != null and thread 2 knows it for sure, because the variable “instance” is of type volatile). So no new instances must be created and the method simply returns the unique instance already created by thread 1.

Thread-safe implementation: implicit (Java)

In Java when a class is initialized and loaded into memory for the first time all its static variables are also initialized, and this operation is thread-safe by default.
We can leverage this feature to implement the Singleton Pattern in a thread-safe way…

public class Singleton { 
    /**
    * When this class is loaded into memory the constant INSTANCE is created, and this 
    * operation is thread-safe.
    */
   private final static Singleton INSTANCE = new Singleton();
 
  /**
   * The constructor is private: the creation of instances must be controlled.
   */
  private Singleton() {}
 
  /**
   * Access point to the Singleton.
   */
  public static Singleton getInstance() {
    return INSTANCE;
  }
}


Thread-safe implementation: lazy initialization (Java)

public class Singleton { 
   /**
   * The constructor is private: the creation of instances must be controlled.
   */
  private Singleton() {}
 
  /**
   * The class Container is initialized/loaded into memory when getInstance() is
   * is invoked for the first time, that is when Container.INSTANCE is accessed for
   * the first time and in a thread-safe way.
   */
  private static class Container { 
    private final static Singleton ISTANCE = new Singleton();
  }
 
  /**
   * Accesso point to the Singleton. It makes sure that the constant INSTANCE is created
   * only one time (Singleton) and only when this method is invoked, not before.
   */
  public static Singleton getInstance() {
    return Container.INSTANCE;
  }
}

The last implementation was first introduced by Bill Pugh and uses the so called “lazy initialization”. The idea is to create the unique instance of the Singleton class only when really needed, namely when the method getInstance() is invoked, and not before (in the “Tread-safe implementation: implicit” implementation, that we have seen before, the instance is immediately created when the class is initialized and loaded into memory).  The trick is to create an inner class, Container, containing our Singleton instance. The Singleton instance is created when we refer to the inner class for the first time, that is when the method getInstance is invoked, and not when the outer class is initialized and loaded into memory like in the previous implementation.