The Facade Pattern

The Facade Pattern exposes several components through a single interface. The goal is to simplify the API for the client components.

Let’s say we want to make a robot. A robot is made out of different parts. Our code may look like:

public class SimpleArm implements Arm {

  public SimpleArm() {
  }

}

public class Robot {

   private Arm arm;

   public Robot(Arm arm) {
     this.arm = arm;
   }

   public void moveArm() {
     ...
   }
}

Now this code looks simple, but it could be more complex if the Arm is complicated to be instantiated… and if we add more parts to our robots that are configurable. And we can even have a complex robot made of other robots. Instead of forcing the client code to create the different parts and “assemble” them in the Robot class, we can offer a facade class that requires only a few parameters, instantiate the different parts and offer simple methods to move the robot. The only disadvantage is the possible lack of flexibility for optimization and specification.

The Decorator Pattern

The idea is to augment an existing class with new functionalities without rewriting the existing code. There are two possibilities to do it:

Solution 1: Inherit if the class is not final.

Solution 2: Add a decorator class using composition.

Let’s say we want to program a draw shapes. We can create a Display interface that will be implemented by all of our classes.

public interface Display {

  public void draw();

}

Our basic class draws the shape

public class SimpleDisplay implements Display {

   public void draw() {
     // draw shape
   }

}

Now we want to fill the shape. We can extend what SimpleDisplay does with another class:

public class FillerDisplay {

   private Display display;

   public FillerDisplay(Display display) {
     this.display = display;
   }

   public void draw() {
     fill();
     display.draw();
   }

}

We can also add a zoom effect:

public class ZoomDisplay {

   private Display display;

   public ZoomDisplay(Display display) {
     this.display = display;
   }

   public void draw() {
      zoom();
      display.draw(); 
   }

}

So we can combine those decorators to obtain the result we want:

// a simple display
Display simple = new SimpleDisplay();

// a display filling the shape
Display fill = new FillerDisplay(new SimpleDisplay());

// a display that can zoom
Display zoom = new ZoomDisplay(new FillerDisplay(new SimpleDisplay()));

Notice we do not have to have a filler. A display can simply draw a shape and zoom. There are also ways to simplify the creation of the objects.

What can be trickier is accessing methods in one of the layers. For example, we can imagine that we want the FillerDisplay to use an image to fill the shape. In that case, we would add a method called setImageBackground() but it would be specific to FillerDisplay. To access that method, we would need to implement a getDisplay() in each layer, and we would have a code that looks like:

display.getDisplay().getDisplay()... getDisplay().setImageBackground(img)

which is not … very pretty … (Coding is art after all). What’s possible is to create a “shortcut” method in the client code if it is used frequently:

private Display getFillerDisplay() {
   return display.getDisplay().getDisplay()... getDisplay();
}

It can be lengthy code if each display is a generic:

LayerDisplay<ZoomDisplay<FillerDisplay<RandomDisplay<SimpleDisplay>>>>> display;

hmmm… so good. 🙂

The Composite Pattern

The Composite Pattern creates a mechanism for trading individual objects and compositions of objects in a uniform manner.

What the heck is this definition!?? This is why programming sounds crazy for some. It is sometimes difficult to define programming concepts simply and concisely.

What this composite pattern seeks to do is to handle objects that are composed of other “similar” objects. It is actually very simple. Simply think of a tree of objects with the same behavior. Let’s say we want to know how much each employee, manager, and branch of a bank manages.

public class Employee {  // Leaf
   public double calculatePortfolio() { ... }
}

public class Manager {  // Composite
   private List<Employee> employees;
   private List<Managers> managers; // a manager can manage other managers
   public double calculatePortfolio() { 
     return employees
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
     + managers
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
   }
}

public class Branch { // Other composite or component
  private List<Manager> managers;
  public double calculatePortfolio() {
    return managers
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
  }
}

By calling the calculatePortfolio method, we are able to get the amount of money managed at each level of the tree.

The Bridge Pattern

The Bridge Pattern decouples an abstraction from its implementation to enable the two to vary independently. It puts abstraction and implementation in separate class hierarchies. Instead of implementing the abstraction, the “implementation” uses it.

Let’s illustrate it. We want our software to draw maps which are constituted of different shapes (points, lines, polygons, etc.). We could create a Renderer interface with implementations for each shape:

The problem with this design is that we multiply implementations for each shape. To avoid multiplying classes (one of the pattern’s advantages), we can use the bridge pattern:

The bridge is Renderer/Shape

The code would look like:

class Shape {
  private Renderer renderer;
  private int radius;

  public Shape(Renderer renderer, int radius) {
    this.renderer = renderer;
    this.radius = radius;
  }

  public void draw() {
    renderer.drawCircle(radius);
  }
}

// code using the bridge
FlashyRenderer renderer = new FlashyRenderer();
Shape point = new Point(renderer); // which sets the renderer in the class
point.draw();

renderer.updateColor(); // the body of this method may request the shape to re-draw

When to use it?

  • When we multiply classes having the same behavior on similar objects.
  • When abstractions and implementations must be extensible independently.
  • When the implementation must be selected or changed at run-time.
  • When the implementation has no impact on client code.

The Adapter Pattern

When I used to live in France and travel in the US, I had an adapter for my phone charger since the electrical outlets are different: shape, voltage, etc. The Adapter Pattern does the same. It aims to wrap an existing interface to conform it to a required interface.

Let’s consider this company with a CEO, a manager (the “adapter”) and a programmer:

interface CEO { // implementations: bossyCEO, micromanagerCEO, etc. 🙂
  public Demand command();
}

interface Programmer { // implementations: rebelliousProgrammer, etc.
  public void execute(Expectation cmd);
}

interface Manager { // implementations: terrorizedManager, angryManager, etc.
  public void hear(Demand demand);
  public void execute();
}

// adapter class
class SmartManager implements Manager {

  private Programmer programmer; // would not be private if CEO is micromanaging 🙂
  private Project project;

  public SmartManager(Programmer programmer) { // only one programmer 🙂
    this.programmer = programmer;
  }

  public void hear(Demand demand) {
      decrypt(demand);
      discuss(programmer, demand);
      project = plan(demand);
  }

  public void execute() {
    Expectation expectation = project.getPlan();
    programmer.execute(expectation);
  }  
}

The adapter usually wraps the interface it adapts to transform the calls from the consumer interface.

This pattern may require the creation of temporary objects to handle the “adaptation” which impacts performance (time and resources). If it is the case, caching those temporary objects will help.

In our illustration, Project is a temporary object which was created by the plan(Demand demand) method. We could cache project if the CEO has the same demand.

private Map<Demand, Project> plans;

private Project plan(Demand demand) {
  project = plans.get(demand);
  if (project == null) {
     project = ... // create a new project
     plans.add(demand, project); // cache
  }
  return project;
}

The Singleton Pattern

The Singleton Pattern provides only one instance of a class. It is useful when we want to centralize a certain behavior such as querying the database or writing in files.

First, we want to make sure we create only one instance. The basic pattern looks this way:

public class Singleton {

  private static final Singleton INSTANCE = new Singleton();

  private Singleton() {} // not possible to call the constructor from outside the class

  public static Singleton getInstance() {
    return INSTANCE;
  }
}

There are problems with this though. It is possible to create more than one instance by using:

  1. the Reflection API
  2. Serialization. The JVM does not care about the private constructor when serializing/deserializing. To fix this, we just need to add the readResolve method:
protected Object readResolve() {
  return INSTANCE; // return the existing instance instead of creating a new one.
}

For Serializable classes, the readResolve method let us replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.

Second, we want to guarantee a lazy initialization. We want to make sure we only create the instance when we need it. It can be as simple as:

publics static Singleton getInstance() {
  if (instance != null) {
    instance = new Singleton();
  }
  return instance
}

Third, we want to guarantee thread safety. In the previous case, if there are multi-threads and they access the method at the same time, they may create their two instances (one for each thread). It is possible to create an inner static Singleton using a nested class:

class Singleton {

  private Singleton() {}

  // Nested class 
  private static class Builder {

     private static final Singleton INSTANCE = new Singleton();

     public Singleton getInstance() {
       return Builder.INSTANCE;
     }
  }
}

It is also possible to use enum instead of class. Using an Enum solves the issue with the Reflection API, but it does not allow you to persist an internal state through serialization despite the fact that all the enum are serializable. For example:

public enum Singleton {
  INSTANCE; // name of the enum
  
  Singleton() { // Constructor is always private
    // constructor if needed
    myState = "VALUE"; 
  }

  private String myState;
  public void setValue(String myState) {
    this.myState = myState;
  }
}

If you set the value of myState before serializing the enum, the deserialization will return to the default value set in the constructor which is here “VALUE.” This is a possible limitation for using enum (as well as the impossibility to create subclasses).

Good tips about using a singleton

  • When to use a singleton? For example, we want to create a class that manages displaying maps. Should I use a singleton or a regular class? It seems it could be a singleton. A few questions can help decide:
    • Does the instance access resources that are shared?
    • Should we limit the creation of this class to only one instance? (What if we want to create another map section?)
    • Is it worth the effort to make it thread safe?
  • How to handle resources in the Singleton? A good idea is to use the principle of dependency injection to be able to test the Singleton as well as making sure it is adaptable. Let’s illustrate it quickly with a singleton managing database connections:
enum dbConnector {
  INSTANCE;
  ... // constructor

  public Connection getConnection() {
    DB database = new DB("Oracle"); // hardwire dependency
    return database.getConnection();
  }
}

We can inject the dependency to the database:

enum dbConnector {
  INSTANCE;
  ... // constructor

  public Connection getConnection(DatabaseManager dbMgr) {
    DB database = dbMgr.get("Oracle"); // the dependency is injected
    return database.getConnection();
  }
}

The Prototype Pattern

The Prototype Pattern has purpose to simplify the creation of complex objects by copying them. An existing (partially or fully constructed) design is a Prototype. Let’s illustrate this with a Recipe object:

class Recipe {
  List<String> ingredients;
  List<String> utensils;
  int timeToPrepare;
  int timeToCook;

  ...
}

Let’s say we want to create a bunch of cake recipe. We want to create a basic recipe that can be completed later:

Recipe prototypeCake = new Recipe();
prototypeCake.addIngredient("Flour");
prototypeCake.addIngredient("Eggs");
...
prototypeCake.addUtensil("Bowl");
prototypeCake.addUtensil("Mixer");
...

Now time for the most complex part of the pattern: cloning the prototype. It requires to deep copy every single property (when needed).

class Recipe {
   ...

   public static Recipe clone(Recipe toClone) {
      Recipe copy = new Recipe();
      copy.timeToPrepare = toClone.timeToPrepare;
      copy.timeToCook = toClone.timeToCook;
      toClone.ingredients.forEach(copy::addIngredient);
      toClone.utensils.forEach(copy::addUtensil);
   }
}

// The creation of other recipes becomes much easier
Recipe chocolateCake = Recipe.clone(prototypeCake);
...
Recipe strawberryCake = Recipe.clone(prototypeCake);
...
Recipe cheeseCake = Recipe.clone(prototypeCake);
...

The difficulty with cloning is the to figure out how to copy the whole tree of objects that is needed. What if the list of ingredients was not a list of String but of Ingredient objects?

List<Ingredient> ingredients;

class Ingredient {
  double quantity;
  String description;
  Quality quality;
  double price;
  ...
}

We would need to deep copy Ingredient, and Quality, etc… Another way to clone is to use Java’s serialization mechanism which allows to copy the whole tree of objects by values.

So now, we can customize the objects:

chocolateCake.addIngredient("Chocolate");
etc...