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

The Faceted Builder Pattern

The Faceted Builder Pattern is a sub pattern of the builder pattern. Its purpose is to clarify the construction of a complex object “fluently.” Let’s say we want to build a User object with its personal data (personal info, address, education and education). This pattern enables us to have this:

User user = new UserBuilder()
   .called()
      .firstname("Matthew")
      .middlename("Fred")
      .lastname("Dupont")
   .lives()
      .address("123 rue de la pomme")
      .city("Montauban")
      .postalcode(42331)
      .state("Occitanie")
      .country("France")
   .studied()
      .elementary("Ecole Municipal de Paul Laffort")
      .middleschool("College Pourvoira")
      .highschool("Le Bac de Demain")
      .university("Polytechnique")
   .build();

The idea is to define a UserBuilder class that will have three subclasses: UserInfoBuilder, UserAddressBuilder, UserEducationBuilder:

class User {
  // all fields here...
  private String firstname;
  private String lastname;
  ...

  User(UserBuilder builder) {
    this.firstname = builder.firstname();
    ...
  }

}

class UserBuilder {
   public UserInfoBuilder called() { // return info builder to set info
      ...
   }

   public UserAddressBuilder lives() { // same for address
      ...
   }

   public UserEducationBuilder studied() { // same for education
      ...
   }

   public User build() {
     return new User(this);
   }
}

// since UserInfoBuilder extends UserBuilder, we can call lives()
// or studied() once we are done setting up the personal info
class UserInfoBuilder extends UserBuilder { 

   private String firstname;
   ...

   public UserInfoBuilder firstname(String firstname) {
      this.firstname = firstname;
   }
   public UserInfoBuilder middlename(String ...) // same
   public UserInfoBuilder lastname(String ...) // same
}

class UserAddressBuilder extends UserBuilder {
   private String address;
   public UserAddressBuilder address(String address) {
      this.address = address;
   }
   public UserAddressBuilder city(...) // same
   public UserAddressBuilder postalcode(...) // same
   ...
}

class UserEducationBuilder extends UserBuilder {
   ...
   public UserEducationBuilder elementary(...) {
      ...
   }
   
   ...
}

That’s all!

The Design Pattern Gamma Categorization

Design patterns are usually categorized in three categories:

Creational Patterns

  • Manages construction of objects
  • Can be explicit (ex: constructors) or implicit (ex: Dependency Injection, reflection, etc.)
  • Single statement vs step-by-step process

Structural Patterns

  • Focuses on relationships between objects. They seek to define structures.

Behavioral Patterns

  • Focuses on communications between objects.
  • Deals with assigning responsibilities, encapsulating behavior, delegation, etc.

A pattern can belong to more than one category. A design pattern usually focuses on one main issue and proposes a solution that offers flexibility (easy to maintain and to improve) and reusability.

SOLID* Design Principles (by Robert C. Martin)

Single Responsibility Principle (SRP) / Separation of Concerns

A class is responsible for doing only one thing. Why? The code is cleaner, easier to maintain, and reusable. For example, instead of having a class storing data and persisting it in a file, we can create two classes: a store class and a persistence class.

Open-Closed Principle (OCP)

A class should be open for inheritance, but closed for modification. For example, we want to create a chef class that can make meals. We could define methods like makePizza(), makeCurry(), etc. but it would violate the OCP. Each time, we would need to modify the chef class each time we need to add a new type of meal. A better design would be:

class Chef() {
   Meal make(pizza, recipe);
}

In this case, we do not need to modify chef if we want another type of meal. We would simply give a different recipe. We can also extend Chef if we want to have a FasterChef or FancyChef, etc.

Liskov Substitution Principle (LSP)

A parent class should be substitutable by a subclass. Or according to Barbara Liskov – which is clearer to me :

Let Φ(x) be a property provable about objects x of type T. Then Φ(y) should be true for objects y of type S where S is a subtype of T.

Why? to guarantee that the subclass follow the same behavior as its parent, and to avoid introducing bugs by overriding methods.

class Car() {
   boolean engineOn; // default value = false

   void turnKey() {
     engineOn = true;
   }

   void start() {
      turnKey();
   }

   boolean isOn() {
     return engineOn;
   }
}

class Ferrari() extends Car {
   void start() {
     pressButton(); // no key
   }
   ...
}

class Driver() {
   void use(Car car) {
      car.start();
      if (!car.isOn()) {
        System.out.println("Not working...") 
      }
   }
}

driver.use(ferrari) -> would write "Not working..." because the subclass does not extend its parent's behavior properly which means it is not substitutable.

Interface Segregation Principle (ISP)

An interface must only include methods defining a specific behavior. Or in other words: YAGNI = You Ain’t Going to Need It! Why? to avoid unclear and unimplemented methods when not needed.

Let’s say we want to create a Car interface:

public interface Car {
  void start();
  void drive();
  void removeSeats();
}

This interface may work for a MiniVan class, but not for a Coupe:

public class MiniVan implements Car {
  void start() {
    // do something
  }

  void drive() {
    // do something
  }

  void removeSeats() {
    // do something
  }
}

public class Coupe implements Car {
  void start() {
    // do something
  }

  void drive() {
    // do something
  }

  void removeSeats() {
    // do NOTHING! --> cannot remove seats in a coupe
  }
}

It is better to define two interfaces defining its own behavior:

public interface Drivable {
  void start();
  void drive();
}

public interface Expandable {
  void removeSeats();
}

// As result, we have:
public class MiniVan implements Drivable, Expandable ...
public class Coupe implements Drivable ...

Dependency Inversion Principle (DIP)

This principle (not to be confused with dependency injection) has two parts:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.

The purpose is to avoid dependency from high-level modules on low-level modules. Otherwise, changes on those low-level modules imply refactoring high-level modules. In summary:

High-Level modules -> Interfaces/Abstractions -> Low-Level modules

Let’s say we want to write a reader class (high-level) that represents someone who reads a book.

class Reader {
  private Book book;
  private int currentPage;

  void openBook(Book book) {
     this.book = book;
     this.currentPage = book.open();
  }

  void read() {
     String text = book.readPage(currentPage);
  }

  void turnPage() {
     currentPage++;
     book.gotToPage(currentPage);
  }

}

This class relies on a Book class (low-level):

class Book {
  int open() { ... }
  String readPage() { ... }
  void goToPage() { ... }
}

Now, what happens if instead of a book, our reader wants to read a PDF? or a eBook? or anything else that is readable? We would need to refactor our Reader class. A better version of our code would be:

interface Readable { // our abstraction layer between high and low level
   void open();
   String read(int size);
   void goTo(int location);
}

class Reader {
   private Readable material;
   private int location;
   private final int sizeIcanHandle = 1000;

   void openBook(Readable material) {
     this.material = material;
     this.location = material.open();
   }

   void read() {
     String text = material.read(sizeIcanHandle);
   }

   void next() {
     location += sizeIcanHandle;
     material.gotTo(location);
   }
}

Book, eBook, PDF, etc. classes can implement the Readable interface, and Reader would not need to be rewritten.

Now in real life, I have often seen a multitude of interfaces with only one implementation. Of course, one day we may need another implementation, but most of the time, it sits there and we are not going to need another implementation (by the time we do, we may have already been in an effort to rewrite the whole application), or the interface needs rework (because we do not plan well for unknown future) and debugging becomes tedious. I do not mean to say abstractions are useless, but I sometimes wonder about the benefits vs the costs. Do we really need to be “systematic” in our coding approach? Again, coding is a bit artsy, no matter what developers may say…

*Now you should know what SOLID stands for.

The Observer Pattern (or Publisher-Subscriber)

The “Gang of Four” defines it as “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically” (1).

Why would I need such a thing? Let me illustrate the answer.

When I was a teenager, mobile phones were not yet available. My friends and I decided to spend our Saturday afternoon at the mall. We called each other to set up a time and place where to meet. When I got there, I saw no one. After waiting for a while, I decided to leave. Once at home, I called one of my friends who told me they had cancelled. Someone called someone else, who called someone else while the other one called another person, etc. Unfortunately, by the time I was supposed to get the message, I was already in the city bus.

It would have been great to have a Facebook group that we all joined, and get the cancellation message quickly. You see the problem was that the message somehow got lost between friends. Maybe some got busy with other things. Maybe others forgot to update me, or thought someone else had done it before, etc.

That’s where the Observer pattern is useful. My illustration is not a perfect fit though, but let’s say the person who cancelled was the leader of the group. He is the one in command, and he decides what to do. In the Observer pattern, he is usually called the “subject,” and each member of the group “observer.”

The observer decide to get notifications from the subject.

public class GroupLeader {
  public void attach(Observer obs) {
    // add to the list
  };

  public void detach(Observer obs) {
    // remove of the list
  }

  public void notifiy() {
    // go through the list and notify each observer of a change
    for each observer:
      observer.update("this is the new message")
  }
}
public class GroupMember {
  public void update(String message) {
    // do something
  }
}

The advantages are:

  1. Each member receives the same message.
  2. Each member do not need to worry about the others.
  3. Each member can be responsible for their own task

This pattern is a top-bottom behavior. There is only one who can send messages. A better design pattern for group messaging may be the Mediator Pattern where multiple objects can send messages to others. Which one should you choose? It really depends on what you are trying to accomplish.

(1) John Vlissides; Ralph Johnson; Erich Gamma; Richard Helm. Design Patterns: Elements of Reusable Object-Oriented Software. Published by Addison-Wesley Professional, 1994, p. 293

Constructors vs Static Factory Method

I have wondered if this topic was relevant. I have often seen both ways to create an object. Why bother choosing between a static factory method and a constructor? It seemed to me that they do more or less the same, and the advantages of the static factor method were not so obvious. Why not using the constructor to do what it was invented for: constructing objects?! The choice did and still does feel a bit artsy (=preference). But let me list a few pros for the static method, and you may change your mind.

Advantage #1: name it!

How the heck is this more advantageous? Well, clarity. You can name your static method in a way that means what it is doing. For example, if you want to build a new garden, you can write:

Salad salad = Salad.from(lettuce);

instead of

Salad garden = new Salad(lettuce);

Hmm?? Was it better? Ok, fine. Not that much. But if you need arguments to create your object, you may have factor methods with different names. It can be particularly useful when the parameters are of the same type. For example, I want to make a salad:

public Salad(Green lettuce, Green spinach) {
// do something
}

Now if I want to make a salad with a different mix of green assuming it requires a different behavior, it will look like:

public Salad(Green lettuce, Green roman) {
// do something else
}

The signature is the same. Of course, we could figure out something else. If we have static methods, it will look more elegant:

Salad salad = Garden.makeDarkGreenMix(lettuce, spinach);
Salad salad = Garden.makeLightGreenMix(lettuce, roman);

Well, this example was not very elegant…

Advantage #2: save resources!

A static factory method does not have to create an object. The common example is the getInstance() method Java developers often use to create Singletons.

public static SaladChef getInstance() {
  if (chef == null) { // chef = private SaladChef property
    chef = new SaladChef();
  }
  return chef;
}

Another example would be a pool of connections. etc. It might help to avoid using resources.

Advantage #3: return a subclass!

A static method can return a subclass, but not the constructor. It may help to manage the types of objects return depending on the parameters.

public static Macbook buy(double amount) {
  if (amount < 1000) {
    return new MackbookAir();
  } else {
    return new MacbookPro();
  }
}

But there are two cons: classes without public or protected constructors cannot be inherited, and static factory methods are harder to find than constructors.

Honestly, I still question the systematic use of static factory methods. It is a nice way to code, but it must be used with caution. And I think it is still a matter of art.