The Mediator Pattern

The Mediator pattern facilitates communication between components without having references to each other. It avoids tight coupling between components and helps maintainability.

Let’s say we are building a user interface to visualizes photos. There are multiple components such as the image, the title, the author, the image exif info, the comments, the thumbnail bar, etc. When a user selects a new image, all those components need to be updated. Without the Mediator pattern, the “next” button would call all the components to update them.

public class NextButton {

private Display imageDisplay;
private Label title;
private Label author;
...

public onClick() {
// some code to get the image
imageDisplay.goto(image);
title.set(image);
author.set(image);
// etc...
}
}

We can also imagine that adding a comment would update the title of the image with the total count of comments. It would mean that the comment section has a reference on the title. All those components would be tightly linked.

The Mediator pattern introduces a new component which would be the only one with references to all the different components. Whenever a component needs to communicate with the others, it would send a message to the mediator which then dispatch it to the others.

In our case, the click on “Next” would send an event.

public class NextButton implements UIComponent {

 private EventBroker mediator;

 public void onClick() {
     // some code to get the image
     mediator.publish(new Event("updateImage"));
 }

 public void listen(Event e) {
   // do something when necessary
 }
}

The mediator would then publish the events to all the components that are listening.

public class EventBroker {
    private List<UIComponent> components;

   public void subscribe(UIComponent component) {
     components.add(component);
   }

   public void publish(Event e) {
     components.foreach(it -> it.listen(e));
   }
}

The Iterator Pattern

The iterator pattern allows the client code to traverse data collections without exposing their structure. The client code does not need to know how the data are stored, and how to go from one element to another.

This pattern usually defines an Iterator class which keeps a reference to the current element and is able to go to the next element. Java has its Iterator interface that many collection classes implement.

Iterator<Car> it = mylist.iterator(); // retrieve iterator object from the collection
while (it.hasNext()) { // browse all the elements
   Car car = it.next(); // return the current element and move on the next element
   // ... do something
}

The Interpreter Pattern

The interpreter pattern evaluates textual inputs. It does it by turning it into separated lexical terms (lexing) and interpreting each sequence (parsing). You can think of programming languages, or languages meant to carry information such as XML.

For example, we want to calculate the result of this formula: 1+3+5*7

First, we need to find the terms: [1,3,5,7] and the operations: [+, +, *]

Second, we interpret them into a logical sequence: add(add(1,3),multiply(5,7)).

The idea is to single out terms and operations in order to simplify and make the design flexible to different inputs (ex: term order, etc.)

The Command Pattern

The Command Pattern is useful to implement an instruction to perform a particular action. It contains and encapsulates all the information necessary for the action to be taken. It can allow to create composite commands, to keep track of a sequence of commands, and possibly to undo one of the commands. It can be used in GUI or transactions for example.

Think of a text editor. We can type characters and format them. Each command will implement an interface:

public interface Command {
   void perform();
   void undo();
}

public class Write implements Command {

   private TextEditor editor; // we will assume this class exists.
   private String string;
   private boolean success;

   public Write(TextEditor editor, String string) {
      this.editor = editor;
      this.string = string;
      this.success = false; // by default, a boolean is false, but it does not hurt to make it explicit!
   }

   @Override
   public void perform() {
       editor.write(string);
       success = true;
   }

   @Override
   public void undo() {
      if (success) { // we do not want to undo if the operation failed
        editor.erase(string); // more complex in reality, but not the purpose of this example.
      }
   }
}

public class Formatter implements Command {

  public enum Format {
     BOLD,
     ITALICIZE
  }

   private TextEditor editor;
   private Format format;
   private int startPosition; 
   private int endPosition;
   private boolean success;

   public Formatter(TextEditor editor, Format format, int startPosition, int endPosition) { // could chain with Write.. Chain of responsibility pattern!
      this.editor = editor;
      this.format = format;
      this.startPosition = startPosition;
      this.endPosition = endPosition;
      this.success = false;
   }

   @Override
   public void perform() {
      switch (format) {
         case BOLD:
           success = editor.bold(startPosition, endPosition);
           break;
         case ITALICIZE:
           success = editor.italicize(startPosition, endPosition);
           break;
         default: 
           break;
      }
   }

   @Override
   public void undo() {
      if (!success) return; // we do not want to undo if the operation failed
      switch (format) {
        case BOLD:
          editor.unbold(startPosition, endPosition);
          break;
        case ITALICIZE:
          editor.unbold(startPosition, endPosition);
          break;
        default:
          break;
      }
   }
}

The client code can chain commands or undo, etc.

TextEditor editor = new TextEditor();
Command awesome = new Write(editor, "This is awesome!");
Command author = new Write(editor, "By John Doe");
Command formatAwesome = new Formatter(editor, Formatter.Format.BOLD, 8, 15); 
Command formatAuthor = new Formatter(editor, Formatter.Format.ITALICIZE, 16, 27);

List<Command> cmds = new ArrayList<>();
cmds.add(awesome);
cmds.add(formatAwesome);
cmds.add(author);
cmds.add(formatAuthor);

try {
  cmds.forEach(Command::perform); // run
} catch (Exception e) {
  Collections.reverse(cmds); // reverse the command sequence.
  cmds.forEach(Command::undo); // will undo only those that succeeded.
}

This pattern can be combined with the Chain of Responsibility pattern or the Strategy pattern.

This is awesome! But is it really useful you could ask? What about just calling TextEditor’s methods? True! I was wondering the same. What is really powerful is how we can manage those commands. It can be more complex commands, sequenced, and we can create rollbacks, etc.

The Chain of Responsibility Pattern

The Chain of Responsibility pattern is useful when there is a chain of components that need to accomplish the same operation. Each component may have a default implementation and/or cancel the processing chain.

Let’s say we want to write a class that handles http requests. For each request, we want to log it, verify its authentication, and parse the content. Each operation can be designed as a class implementing the same interface.

public interface HttpRequestHandler {

   HttpRequestHandler next();
   void setNext(HttpRequestHandler next);

   // allows to chain other handlers
   default void add(HttpRequestHandler handler) {
      if (next() != null) {
        next().add(handler);
      } else {
        setNext(handler);
      }
   }; 

   void process(HttpRequest request);
}

public class Logger implements HttpRequestHandler {

   private Log log = ...
   private HttpRequestHandler next;

   // implements getter/setter
   // ...

   public void process(HttpRequest request) {
      log.log(request); // order can changed if we want the operations to start at the end of the chain
      if (next != null) next.process(request);
   }
}

public class Authenticator implements HttpRequestHandler {

    private HttpRequestHandler next;

    // implements getter/setter
    // ...

    public void process(HttpRequest request) {
      if (authenticate(request)) {
         if (next != null) next.process(request);
      }
      // the chain is disrupted if the request does not pass the security check
    }

    private boolean authenticate(HttpRequest request) {
      // ...
    }
}


public class Parser implements HttpRequestHandler {

    private HttpRequestHandler next;

    // implements getter/setter
    // ...

    public void process(HttpRequest request) {
      parse(request);
      if (next != null) next.process(request);
    }

    private void parse(HttpRequest request) {
       // ...
    }
}

The good thing with this design is that we can add more operations without too much effort. Now we can have our client code manipulating the handlers:

public class WebServer {

   public HttpResponse respondTo(HttpRequest request) {
      handlers().handle(request);
   }

   private HttpRequestHandler handlers() {
      Logger logger = new Logger();
      Authenticator auth = new Authenticator();
      Parser parser = new Parser();
      logger.add(auth);
      logger.add(parser);
      return logger;
   }

}

The Proxy Pattern

The Proxy pattern creates an interface giving access to a resource to hide any underlying-complexity as well as to add improvements of the underlying code. The proxy interface looks like the interface it “caches.”

Let’s think about a query object we want to use to query a database. It is great to log any request for debugging purpose.

public class SimpleQuery<T> implements Query<T> {

   public T findBy(String id) { 
       // connect to database, query, etc.
       return db.query(sql);
   }

   public void insert(T object) {
       // connect to database, create id, etc.
       db.insert(sql);
   }
}

We are going to proxy this with inheritance. It is possible to implement this pattern with other techniques such as composition (having a reference of the object to proxy), or introspection if we want the proxy to be dynamic (done at runtime).

public class ProxyQuery<T> extends SimpleQuery<T> {

   private Logger logger = ... // whatever framework you want to use
   
   public T findBy(String id) {
     // connect to database, query, etc.
     String sql = "select * from table where id="+id;
     logger.debug(sql);
     return db.query(sql);
   }

   public void insert(T object) {
     // connect to database, create id, etc.
     String sql = "insert into table (id, value) values ("+id+","+object+")";
     logger.debug(sql);
     db.insert(object);
   }

}

And that’s all! Of course proxies can be much more complex. It can be used to call a remote object. It can be used to use a cache, etc.

Now you may wonder: what is the difference between the proxy pattern and the decorator pattern?

  • The proxy pattern provides an identical interface while the decorator provides an enhanced interface.
  • The decorator usually aggregates (composition) what it is decorating. The proxy does not have to work that way.
  • Proxy might interface an object that has not been created yet. For example, you may want to stack up / validate information before creating the actual object for performance sake.

Java Generics and Interfaces

Why are the two related? Because subclasses may need to know what specific class it is handling.

We get confused because we subclass generic interfaces to specify what type of items it is handling. For example, we may want to create a high level interface Renderer<T extends Shape> to draw shapes. Then we want to subclass it for:

SimpleRenderer<Point>: render points. The logical “relation” tree is:

SimpleRenderer<ComplexShape>: render complex shapes. The relations are:

BufferedRenderer<LargeComplexShape>: render large complex shapes . We may think it would work to have:

The purpose is to be able to have a single object manipulating both SimpleRenderer<ComplexShape> and BufferedRenderer<LargeComplexShape> “under” Renderer<ComplexShape>… but it does not work.

The relation tree for large complex shapes is actually:

So we cannot use Renderer<ComplexShape> to manipulate both. Painful, isn’t it?

Here are my suggestions to help design classes:

Suggestion #1: do not think of Generics for inheritance, but to avoid casting object.

Suggestion #2: do I need to know the subclass type? if not, do not use Generics. Use interfaces

The Fluent Builder as Solution to the Builder Pattern and Inheritance

What a title! If you do not know what the builder pattern is, you can look at my post here. A builder can be helpful, but you quickly realize it is painful to handle this pattern with inheritance.

Let’s use this simple example: we want to create classes representing a SUV and a coupe.

public class Car { 

    private Color color;
    private Engine engine;

}

public class SUV extends Car { 

   private FourWheelDriveSystem wdSystem;

}

public class Coupe extends Car {  

   private Door[] twoDoors;

}

We want to use the builder pattern to instantiate SUV and Coupe objects. We could simply duplicate the code from the Car Builder in SUV and Coupe. It may be ok if there are not many properties. But if we want to avoid duplicating, we can create a Car, SUV and Coupe Builders:

public class Car {

  private Color color;
  private Engine engine;

  public static class Builder { // see post on builder pattern for more details
     private Color color;
     private Engine engine;

     public Builder withColor(Color color) { ... }
     public Builder withEngine(Engine engine) { ... }
     public Car build() { ... } 
  }

}

public class SUV extends Car {

   private FourWheelDriveSystem wdSystem;

   public static class Builder extends Car.Builder { 
     private FourWheelDriveSystem wdSystem;

     public Builder withWdSystem(FourWheelDriveSystem wdSystem) { ... }
     public SUV build() { ... }
   }
}

public class Coupe extends Car {

   private DoorSystem twoDoors;

   public static class Builder extends Car.Builder {
      private DoorSystem twoDoors;

      public Builder withTwoDoors(DoorSystem twoDoors) { ... }
      public Coupe build() { ... }
   }

}

So far so good. However, this code fails:

new SUV.Builder()
  .withColor(color) // returns a Car.Builder
  .withWdSystem(wdSystem) // do not compile because the function belongs to SUV.Builder
  .withEngine(engine)
  .build(); // would return a Car object, not a SUV...

One solution is to use Recursive Generics:

// in Car class
public static class Builder<SELF extends Car.Builder<SELF>> {

  public SELF withColor(Color color) { 
    this.color = color;
    return (SELF) this;
  }
  ...
}

// in SUV class
public static class Builder extends Car.Builder<Builder> {

  public Builder withWdSystem(FourWheelDriveSystem wdSystem) { 
     this.wdSystem = wdSystem;
     return this;
  }

}

Now the code works:

new SUV.Builder()
   .withColor(color) // now returns a SUV.Builder
   .withWdSystem(wdSystem) 
   .withEngine(engine)
   .build(); // would return a SUV object

Et voila! But it takes a bit of brain power to understand for a programmer who has not developed the code to understand what the builder does…

The Flyweight Pattern

The flyweight pattern seeks to avoid redundancy when storing data. It is a space optimization technique that uses less memory by storing data from similar objects.

Let’s say we want to render the movements of an animal on map based on GPS coordinates collected every 10 seconds from an implanted GPS device. The data collected are represented by a list of GpsPoint:

public class GpsPoint {
  private double longitude;
  private double latitude;
  private double altitude;

  // getters/setters
}

Now we may want to track multiple animals on a single map. The number of points can quickly increase. We can use a buffer to keep in memory duplicated points. Indeed, the animal may stay or go back to the same spots. Our buffer can be very simple:

public class Buffer<GpsPoint> {

   private List<GpsPoint> points;

   public boolean contains(GpsPoint point) {
      return points.contains(point); // assume GpsPoint overrode equals() and hashcode()
   }

   // ...
}

We would need a buffer manager or the renderer can manage the buffer. For example, it would check if the point exists in the buffer before adding it:

public class Renderer {

   private Buffer<GpsPoint> buffer;

   public void render(GpsPoint point) {
       if (!buffer.contains(point)) { // does not keep duplicate in memory
          buffer.add(point);
       }

       buffer.forEach(pt -> drawPoint(pt)); // render each point of the buffer
   }

}

Buffer has less points than what the trace has. Simple technique… the most complicated part of this pattern is probably its name 🙂

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.