Introducing the Creational Design Patterns

Tram Ho

1. Introduction

In software engineering, Design Pattern describes building solutions to the most common problems in software design. It represents the best practices developed over a long period of time through trial and error by experienced developers.
In this article, we will learn about creational design patterns and their types. We will also take a look at some examples and discuss the conditions that these design patterns are suitable for designing.

2. Creational Design Patterns

Creational Design Patterns are related to the creation of objects. They reduce complexity and instability when creating objects in a controlled way.
The new operator is often considered harmful because it scatters objects throughout the application. Over time, changing implementations can become difficult because the classes become closely linked.
Creational Design Patterns solves this problem by completely separating the client from the actual initialization process
In this article, we discuss 4 types of Creational Design Patterns:

  • Singleton – Ensure that only one instance of the object exists throughout the application.
  • Factory Method – Create objects of several related classes without specifying the object exactly created.
  • Abstract Factory – Create the same related dependent objects.
  • Builder – Build complex objects using a step-by-step method.

3. Singleton Design Pattern

The Singleton design pattern aims to test the initialization of objects of a specific class by ensuring that only one object of an object exists in the Java Virtual Machine.
A Singleton class also provides a unique global access point for the object so that each subsequent call to the access point only returns that particular object.

Example of Singleton Pattern

Although the Singleton pattern was introduced by GoF , the initial implementation was known to be problematic in multithreaded scenarios.
So here, we will take a more optimal approach, using the static inner class:

Here, we have created a static inner class that holds the instance of a Singleton class. It will only create one instance when we call getInstance (), not when the outer class is loaded.
This is a widely used approach for a Singleton class because it requires no synchronization, is thread safe, performs lazy initialization, and has relatively few templates.
Also, note that the constructor has access modifier as private. This is a requirement for creating a Singleton because when a public constructor means anyone can access it and start creating new instances.

When to use the Singleton design pattern

  • For resources that are quite expensive to create (such as database connection objects).
  • It is a good practice to keep all loggers like Singletons increasing performance.
  • Classes provide access to configuration settings for the application.
  • Classes containing reesource are accessed in shared mode.

4. Factory Method Design Pattern

This is one of the most commonly used designs. According to GoF , this design pattern defines an inteface to create objects, but lets the subclasses decide which class to create.
This design pattern delegates the responsibility of initializing a class from the client to a specific class by creating a type of virtual constructor.
To achieve this, we rely on a factory that provides us with objects, hiding details of the implementation. Created objects are accessed using a common inteface.

For example

In this example, we will create an interface called Polygon that will be implements by a specific class. A PolygonFactory will be used to find and retrieve objects of this type:
Let’s create the Polygon interface:

Next, let’s create subclasses like Square , Triangle , … These classes will implement Polygon and return Polygon objects.
Now, let’s create a factory that takes an edge number as the argument and returns the corresponding implementation:

Note how the client can rely on this factory to provide us with an appropriate Polygon without having to instantiate the object directly.

When to use the Factory Method design pattern

  • When implementing an interface or an abstract class is expected to change frequently.
  • When the current implementation cannot easily adapt to new changes.
  • When the initialization process is relatively simple and the constructor requires only a few parameters.

5. Abstract Factory Design Pattern

In the previous section, we saw how to use the Factory Method design pattern to create objects related to a family of objects.
In contrast, the Abstract Factory design pattern is used to create families of related or dependent objects. It is sometimes also called a factory of factories.
The design of this design can be visualized through the following image: To learn more about how to implement, you can refer to the detailed instructions for Abstract Factory

6. Builder Design Pattern

This design focuses on abstraction and is great for handling complex objects, however, the design is a bit complicated.
This example has only one class, BankAccount contains constructor as static inner class:

Note that all access modifiers on the fields are declared private because we do not want external objects to directly access them.
The constructor is also private so only the Builder assigned to this class can access it. All properties set in the constructor are extracted from the builder we provided as the argument.
We define BankAccountBuilder in a static inner class:

Note that we have declared the same set of fields that the external class contains. Any required fields are required as arguments to the constructor of the inner class while the remaining optional fields can be specified using setter methods.
This implementation also supports a smooth design approach by having setter methods returning the builder object.
Finally, the constructor calls the outer constructor’s own constructor and passes itself as an argument. The returned BankAccount will be initialized with the parameters set by BankAccountBuilder.
Let’s look at a simple example of how to use this design pattern:

When to use the Builder design pattern

  • When handling involves creating an object is extremely complex, with lots of required parameters and options
  • As the increase in the number of constructor parameters leads to a large list of constructors
  • When the client wants different representations for the object to be constructed

7. Conclusion

In this article, we learned about creative design patterns in Java. We also discussed their four different types: Singleton, Factory Method, Abstract Factory and Builder Pattern, their advantages, examples and when we should use them.

References

Introduction to Creational Design Patterns

Share the news now

Source : Viblo