Design Patterns Examples in Java – Builder Design Pattern

Builder design pattern

Builder design pattern

Have you ever created an object that has over 20 fields ?, have you ever tried to create this object using it’s constructor with several lines of code ? Have you ever needed to create an object without knowing its exact number of fields ? no worries, meet the Builder design pattern. 

Builder design pattern is an awesome pattern that eases the construction of complex objects.

Why Builder Patter ? 

Telescoping Constructor

Telescoping constructor is an anti-pattern that represents an object with several constructors each with different number of parameters. 

The problem with this telescoping constructor is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation. 

Objects default Values. 

Sometimes we create objects and we are concerned only with few fields, the rest is set to some default values. This pattern is most common in testing. In this case Builder design pattern helps a lot. 

Creating Object in Natural Language

Builder pattern helps building objects in natural language style, which really helps understanding the object’s complex parts during creation.

Not only one way to implement builder design pattern. 

As I mentioned previously, there is no one way to implement a design pattern. It is the idea behind the pattern that matters. 

Builder design pattern

Builder design pattern

The above design patter is described in GoF design patterns. 

The most used form of builder pattern, as some call it, the fluent builder. 

fluent-builder
fluent-builder

 

Where to use Builder design pattern

  • When the algorithm for creating a complex object should be independent of
    the parts that make up the object and how they are assembled.
  • When the construction process must allow different representations for the
    object that is constructed.
  • When you want to insulate clients from the knowledge of the actual
    creation process and/or resulting product.
  • When your object contains Telescoping constructors 
  • When you are concerned with only few properties of the object and the rest can be set to default. 

Drawbacks/consequences

  • Need flexibility in creating various complex objects. Need to create complex,
    aggregate objects 
  • It is time consuming and overhead to create builders. 

Examples from Java 

 

 

Design Patterns Examples in Java – Abstract Factory

abstract factory

Abstract Factory Pattern

In part two I introduced factory pattern, here I introduce abstract factory and most important the differences between the two patterns. Abstract factory adds one abstract level in factory patter. To put it simply, you can view abstract factory as a factory of factories. 

Definition

Abstract factory is a creational design pattern, it adds another abstraction level to factory method by encapsulating a group of factory methods. Abstract factory is used to create a family of related objects – factories that create related object – without specifying their concrete implementation. One more definition, abstract factory is a super factory that creates smaller factories that create related objects. 

 

Example

Let me take my previous example of transportation factory and add one level of abstraction. Lets say we need to group transportation into groups. Cheap transportation, middle cost transportation, expensive transportation and let us have a company for each group that provides a certain type of transportation, CheapTrans, SeemlessTransportation, BestTrans. Our super factory will create other factories (these 3 companies) that will create transportation objects. The transportation objects are the related families of objects, the companies are the factories, the factory that will create these factories is the abstract factory. 

Abstract Factory
Abstract Factory

 

Examples from Java

All of these methods create concrete factories, these factories create concrete related objects.

 

Where to use

The pattern can be used where we need to create sets of objects that share a
common theme and where the client only needs to know how to handle the
abstract equivalence of these objects, i.e. the implementation is not
important for the client. It is often employed when there
is a need to use different sets of objects and where the objects could be
added or changed some time during the lifetime of an application. 

 

Benefits

Use of this pattern makes it possible to interchange concrete classes without
changing the code that uses them, even at runtime. 

Drawbacks/consequences

As with similar design patterns, one of the main drawbacks is the possibility
of unnecessary complexity and extra work in the initial writing of the code.

 

References: 

GoF Design Patterns – with examples using Java and UML2

https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries

 

 

 

 

 

 

 

Design Patterns Examples in Java – Factory Pattern

Creational Design Patterns

Factory Pattern

In part one of this series of design patterns articles we introduced design patterns, here we start with the first category of design patterns, as GOF describes , creational design patterns and the first one of them, is Factory Pattern .  

As the name describes, creational design patterns are about creating objects. They deal with objects creation mechanisms, trying to create objects in a way suitable to the situation. Creating objects using the basic form ( the new keyword in Java ) sometimes creates undesired designs like hard coded values, long constructors, and other complex situations. Creational design patterns tries to solve these problems in the best possible way.   

Definition

Factory Pattern represents an object that creates other objects.

The factory can return an instance of one of several possible classes (in a
subclass hierarchy), depending on the data provided to it. It is the one of the most used and easiest design patterns. Keep in mind that there is no single implementation of factory pattern, there are many. The main idea is still the same ! 

EXAMPLE  

Lets say, you want to create a transportation objects. All of them have a the same function move objects from point A to point B. 

 

factory pattern
factory pattern

Here is a code example: 

A real example: 

Many articles online give only one abstract example of a design pattern that it describes. Most of these examples are abstract ones and doesn’t give a clear picture of the pattern. I am quoting a real code example here.

There are many example of Factory Pattern in Java, here I am listing some of them. It is important to keep in mind that there is not standard exact template to follow to create factory, neither there is for any Design Pattern.  In other words,  if some code is said to be a factory pattern, it doesn’t mean that it will implement the same number of classes and introduce the same number and type of relation. Design Patterns may vary in their implementations but the idea remains the same. In our case the idea is to create objects. 

Factory Pattern Use Cases: 

  1. java.util.Calendar#getInstance()
  2. java.util.ResourceBundle#getBundle()
  3. java.text.NumberFormat#getInstance()
  4. java.nio.charset.Charset#forName()
  5. java.net.URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol)
  6. java.util.EnumSet#of()
  7. javax.xml.bind.JAXBContext#createMarshaller() and other similar methods

As you can see all of the methods in the list create instances, this is the main idea of the this pattern, regardless of the actual real implementation of it.

When to use Factory Pattern

  • When a class can’t anticipate which kind of class of object it must create.
  • You want to localize the knowledge of which class you create.
  • When you have classes that is derived from the same sub-classes, or they may in fact be unrelated classes that just share the same interface. Either way, the methods in these class instances are the same and can be used interchangeably.
  • When you want to insulate the client from the actual type that is being instantiated.

Benefits

  • The client does not need to know every subclass of objects it must create. It
    only need one reference to the abstract class/interface and the factory
    object.
  • The factory encapsulate the creation of objects. This can be useful if the
    creation process is very complex. 

Drawbacks/consequences 

There is no way to change an implementing class without a recompile. 

 

References: 

GoF Design Patterns – with examples using Java and UML2

https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries

Design Patterns Examples in Java – Introduction

Design Patterns

Introduction

This article represents an introduction to the world of design patterns. 

In my collection of design patterns articles, I try to introduce them from a different, more practical angle, than other articles I found online.

Most articles try to explain design patterns in an abstract way, and give approximate examples of them hoping they can be understood. I, on the other side, find it difficult to understand them that way. I prefer to have a real code example of each design pattern. So, let’s get started ! 

What is a pattern ? 

Referring to google translate here is what a pattern is: 

  1. A regular and intelligible form or sequence discernible in the way in which something happens or is done. 
  2. A repeated decorative design
  3. Simply, a pattern represents a repeated collection of actions that happen often in the same way and succession. 

Going to work, school, or university represents a pattern. Waking up every morning, dressing up, using public transport, and getting to work, then leaving it, etc. 

What ARE a design patterns ? 

I don’t want to repeat what you can easy find online. So here are a couple of definitions of design patterns from a few references.  

In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design 

wikipedia

Design patterns are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context. 

The book of GOF

Elements of Design Patterns 

In general, a pattern has four essential elements 

  • The name of the pattern. The name represents a handle that we can use to describe a design problem, its solution, and consequences in simple words.
  • The problem. Describes when to apply the pattern, the problem and it’s context. 
  • The solution of the problem. 
  • The consequences. They are the results and trade-offs of applying the pattern.  

Types of Software Design Patterns  

We can put design patterns into 3 groups considering the kind of problem they solve. 

  • Creational, as the name reveals, the problem they solve is creating something. To be more concrete they create objects. 
  • Structural, these patterns describe how we can combine objects and classes to form structures. 
  • Behavioral patterns, they are patterns that focus on the interaction between cooperating objects.

 Keep in mind 

When it comes to using patterns there are several things one should keep in mind.

  • They are rarely used in real life situations. During my development career, which I don’t consider to be a long one (around 5 years),  I don’t remember using more than 10% of the patterns and I mostly needed them during job interviews. This doesn’t mean they are not important or are inappropriate but in fact very few developers understand and use them correctly. And if they do – they don`t really do it on purpose.
  • Design patterns change over time. Programming languages evolve, new ones come. Many patterns were designed to solve some problem that the language itself produced. We will see examples of these when we put some design patterns in the light of Java 8. 
  • Don’t solve problems that don’t exists. Consider if the problem really exists and if that solution is actually needed. Using design patterns in every piece of code is not a good practice, neither is their overuse.

Next -> Creational Design Patterns