Skip to content

design-patterns

Design Patterns, Builder

The Builder is a design pattern which belongs to the family of creational design patterns. It comes very handy when an object is complicated to create (i.e has too many fields) or when the developer needs to control the initialization of an object.

Using the Builder pattern, the construction of a complicated object is encapsulated and controlled only at one place. That way, the user can modify the creation logic, or even the object, without having to find every place where the object's constructor is called.

Additionally, another use case of the Builder pattern is when some validation on an object's field's value needs to happen prior initialization (e.g email validation).

Take for example the below constructor:

Even though at the moment the constructor does not seem too complicated, imagine in the future the developer needs to add one or more fields. He/She will need to change every line of code that initializes a Person object.

Moreover, what if the developer needs to validate the fields prior to object's construction. Those things can be solved using a builder. I like having the builder as a separate static inner class of the object that it builds.

An example of a PersonBuilder, which performs some validation prior to object creation, is the below:

The full example along with some unit tests can be found on Github.

Design Patterns, Singleton

Singleton, is probably, the most controversial object oriented design pattern. Many people even consider it an antipattern.

It is used when one and only one instance of a class should exist per JVM (or classloader).

I personally believe it is a useful pattern and with some care it can definitely solve more problems than it can introduce ( http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html ).

There are quite a few implementations of the Singleton pattern, most of which are designed around JVM's and Java's intricacies. My favourite one is the lazily initialized one, using the holder idiom. The benefits of this implementation are that the class will only be initialized if and when needed and the thread safety is guaranteed by the language itself.

A sample implementation is the following:

For the complete example along with a unit test please see: Design Pattern Examples