In this article, we provide an introduction to the world of design patterns. For each pattern, we further understand the pattern and the context in which it is applicable, with real-world examples.
In this post, you will learn:
We have been building object-oriented software for over 40 years now, starting with Smalltalk, which was the first object-oriented language.
The programming world has encountered a large number of problems, and a variety of solution have been proposed to tackle them.
An attempt was made by a group of four people, famously called the “Gang-Of-Four” or GoF, to come up with a set of common problems and solutions for them, in the given context.
This catalog of common problems and their solutions is labeled as GOF (Gang of Four) Design Patterns.## Why Design Patterns?
The advantages of design patterns are:
The design patterns we talk about here, are from the perspective of an object-oriented world. There are mainly three different kinds of design patterns:
Creational patterns deal with the creation of objects.
Structural patterns deal with the composition of objects.
It deals with questions such as:
Behavioral patterns focus more on the behavior of objects, or more precisely, interactions between objects.
How does an object communicate with another object?
We explore the following creational design patterns:
A prototype represents a fully initialized instance, to be copied or cloned.
Let’s take an example:
Let’s consider the design of a chess game. Every game of chess has the same initial setup — the king, queen, rook, bishop, knight, and the pawns all have their specific places. Let’s say we want to build software to model a chess game.
Every time a new Chess game is played, we need to create the initial board layout.
Instead of repeating the creation of chess board each time,
The object with the initial setup of the chess board is the prototype. And, we are using the prototype pattern.
Isn’t it simple?
In the prototype pattern, you have a fully initialized instance. Here, the initial board layout is readily available.
Whenever a new chess game is started, for example, in any of the numerous online Chess portals, this initialized instance is merely copied or cloned.
The Builder Pattern separates object construction from its representation. What does that mean?
Assume that you go out for a multi-course dinner to a restaurant. Such a dinner would have many options, such as starters, main course, and desserts. You would probably choose two or three out of the presented options. A particular client may want to have dinner with the first two options only, leaving out the desserts option. Yet, another would prefer the main course and desserts, skipping the starters entirely.
Similar situations might arise in designing software. You may need to build an object using a subset of the options that are available. Or, you may need to create the object in multiple ways. This is where the builder pattern comes in handy.
To understand it further, let’s look at a small piece of code.
Let’s say you’re writing software for a machine that prepares coffee. The main ingredients of coffee are coffee, milk, and sugar.
Depending on which part of the world you are from, you choose whether or not you have sugar and milk.
The builder pattern steps in to provide these coffee options for you.
Have a look at the code inside
What we have inside the
Coffee is a
Builder, to which we pass the mandatory
type of the coffee. Chained to that call, we make other calls adding in our preferences of the other ingredients.
Someone else who wants a different coffee can easily build it. This leads to a huge amount of flexibility in building objects.
Other approaches to solving this problem, such as the use of setters, have many inherent problems. These solution lead to code that is difficult to read, and also behave erratically in multithreaded programs. The builder pattern solves all those problems.
The advantages of using the builder pattern are:
The singleton pattern is the most famous among all the design patterns. What this pattern does is very clear from its name — it allows only one instance of a class per JVM at any point in time.
A good real-world comparison would probably be the leader of a nation.
However, there is a disclaimer here — there can only be one instance of that class, per JVM. If you have a Java application that runs as part of a cluster of application servers, each server runs a separate JVM instance. Therefore, you are allowed to have one instance of the singleton created on each application server, at any given point of time.
There are a few things to remember whenever you create a singleton class.
private, to prevent the possibility of other objects creating instances of your class.
@Singleton, along with other related annotations.
The intent of the factory method pattern is to create a family of object types. Let’s look at a code example.
This code implements a
PersonFactory. This class has a static method named
getPerson() that accepts a person’s name and gender as parameters. Depending on the gender
String passed in, it either returns a
Male or a
If somebody wants to create a male person, they invoke the
getPerson() method on the
PersonFactory with a gender argument of
"M". Similarly, you can create a female person by invoking the
getPerson() method on the
PersonFactory with a gender argument of
We are passing in an identifier of the type of object we need, at the time of creation, while still referring to the generic type,
Female classes are hidden behind the
The advantage of using the abstract method pattern is that you can add additional types to the factory, without much change in the other classes using this class. In our example, you can add more types of gender, without affecting the existing code that deals with other genders, which all use
What about the complexity involved in creating an object?
It greatly simplifies the task of object creation. The
PersonFactory makes the decision of what object to create, and delivers it to us.
Let us now have a look at the structural design patterns we want to explore.
A proxy is an object that represents another object.
Let’s look at a real-world example.
Your debit card is a proxy for your bank account. Whenever you make a transaction using a debit card, the corresponding money is deducted from the bank account.
The debit card is a proxy for your bank account, which is the actual object.
Similar to that, in programming, you might have to program interactions with remote objects. In such situations, you create a proxy object that takes care of all external communications. You would communicate with the proxy as if it were residing on your local machine.
A good example is the EJB Home and Remote interfaces.
A proxy hides the complexity involved in communicating with the real object.
The decorator pattern allows us to add responsibilities to objects, dynamically.
In object-oriented programming, we typically use a lot of inheritance.
Let’s say a particular pizza place has 10 types of pizza. Our implementation has 10 classes for these types of pizza.
Now, there is a requirement to make these pizzas available with three types of toppings. If we would want to create individual classes for each pizza and topping combination, we have a total of 30 classes to manage.
Instead of doing this, can we make the pizza-topping relationship dynamic? Can we add a topping on top of an existing pizza?
We need to use a topping as a decorator on top of any pizza.
Another example would be adding a discount on a pizza order.
Let’s say that you have an order, and based on some criteria, you want to offer a discount to the customer. There might be a variety of discounts that might be applicable at different times. If you add a different type of a discount to each type of order, then in a static relationship, you need to maintain hundreds of classes.
Treating a discount as a decorator on an order makes the relationship dynamic.
A very good example where the decorator pattern is implemented in Java is the Java I/O packages. This is reflected in the way we create an input stream in an I/O program:
You have a
FileInputStream. If you want to make it buffered, then add a decorator to it in the form of a
BufferedInputStream. If you want the buffered
FileInputStream to have line numbers in addition, then add a decorator for a
Decorator pattern enables you to add behavior to existing objects at run time. This allows the user of the interface to decide how they want to create objects.
The drawback of this approach is the complexity involved in creating objects. The user needs to understand a lot of classes and their relationships before being able to use the power of the decorator.
A facade is a single class that represents an entire subsystem.
Let’s take the example of an event manager. An event manager is a go-to person when you want to organize an event. They handle several aspects of an event such as the decorations, food, sending out invitations to guests, music arrangements, and other similar things. The event manager acts as the facade of the event organization subsystem.
Consider the case of a distributed system. You typically have the need for multiple calls across layers.
Take, for instance, a system that offers the service for online book orders. Whenever an order comes in, several things need to be taken care of, such as checking for the stock, reserving the order, accepting the payment, updating the stock, and generating the invoice.
We can create a single facade, such as the order interface, which would manage all incoming orders and provide an interface to the customer.
The advantage of using the facade pattern is that it reduces the number of network calls, as well as reduces coupling among classes.
It succeeds in establishing a transaction boundary between communicating objects. Facades, like services, are good hubs to implement transactions.
As long as the interface of the facade remains the same, the implementation details of the subsystem can change.
An adapter is used to match interfaces of different classes.
Let’s take a real-world example of power adapters.
Problem: If you buy a mobile phone in India, it comes with a charger that only works with power sockets used in India. If you take the same charger to the US, for example, it will not work, as it will not fit into sockets there.
Solution: The solution is to use a travel adapter that you can use with your charger when you travel. You can plug in your charger into the travel adapter, and the travel adapter is used to connect to the socket in a particular country.
Similarly, when you try to talk to a system that uses a different message format or a language, you need an adapter to translate messages.
An interesting example is the communication between a Java program and a web service. Before sending out the data to the service, we need to convert the object into XML or JSON format. We are implementing the adapter pattern!
Let’s consider a few scenarios
In these scenarios, you might not want to create a new instance every time it is needed.
How about caching an instance and reusing it when needed?
A flyweight represents creating a fine-grained instance that is being used for efficient sharing.
A really good real-world example is the public switched telephone network (PSTN).
In the PSTN, there are always a limited number of lines, and for simplicity, let’s assume this number is 10. However, there are thousands of customers that use these lines. Since all 1000 customers would not make calls at about the same time, it is possible to efficiently switch calls coming in, among the existing 10 lines.
In the software world, a good example of a Flyweight pattern is JDBC connections.
A connection pool is a set of connections to the database. The application may be firing a lot of queries, but we don’t create a new connection whenever a new query comes in. As soon as a query comes in, we match it to an available connection, and the query gets fired. Once query execution is done, the connection is released back into the pool.
Using such a tool allows us to avoid the cost involved in creating and closing a connection.
Let us now have a look at the behavioral design patterns.
The Chain of Responsibility Pattern represents a way of passing a request between a chain of objects.#### Example 1
The best example of this pattern can be seen in the exception handling mechanism of most programming languages.
Suppose you have a
method2(), in turn, calls
method3(). Assume that
method3() throws an exception.
method3() has no exception handling, then the exception is passed on to
method2()to handle it. If again
method2() has no exception handling inside it, then the exception is passed on to
method1(). If even
method1() cannot handle it, it gets thrown out of
method1() as well.
Consider a real-world example of a loan approval process.
A bank clerk has permissions to approve loans within a certain amount. If the amount goes above that, then it goes to the supervisor. The supervisor has a similar, albeit larger loan approval limit set for him. If the loan amount exceeds that limit, then it goes to his supervisor, and so on.
With the Chain Of Responsibility pattern, we have a chain of objects that are ready and wait to process requests. When a new request enters the system, it goes to the first object in the chain to attempt processing. Depending on the processing condition, the request travels up the chain and gets fully processed at some level, or maybe not processed at all.
The Iterator pattern is one of the most simple design patterns. You have a set of elements arranged in a collection, and you want to sequentially access those elements. A good example of an Iterator is a TV remote, which has the “next” and “previous” buttons to surf TV channels. Pressing the “next” button takes me one channel in the forward direction, and pressing the “previous” button takes me one channel in the backward direction.
In the programming works, examples of the
Iterator class and the enhanced
for loop in Java are examples of the Iterator pattern.
The state pattern is used to alter an object’s behavior when its state changes.
Take a look at this Java example:
Let’s take the example of a fan wall control. The fan wall control controls the speed with a fan rotates. It has speed levels ranging from 0 to 5. When it is at level 0, the fan does not rotate, and it rotates the fastest at level 5.
When you rotate the knob of the fan control, the level changes, and this causes the speed of the fan to change as well. This is a classic case of a change in state (level) causing a change in behavior (speed).
FanwallControl object is composed of a
SpeedLevel is an interface that has four different implementations. Initially, the level is at
Off, and when you click rotate at that time, the new speed is at
SpeedLevel1. The happens successively, and if you rotate at
SpeedLevel3, the level returns to
In case you need to define an additional speed level, just add in a new class that implements the
SpeedLevel interface and implement its rotate method.
This is an excellent example that highlights the advantages of an extensible class.
The strategy has the task of encapsulating an algorithm inside a class. Let’s look at a Java code example:
ComplexClass intends to perform a lot of complex logic within it. One part of that logic is to sort a set of values. One direct way would be to implement the entire sorting logic within
ComplexClass. This would make it very inflexible since, if you wanted to change the sorting logic tomorrow, that entire code needs to change.
When we use the strategy pattern, we separate the algorithm of how the sorting is done from
We define an interface named
Sortable, which has a method named
sort(). Any actual sort algorithm is an implementation of
Sortable, and needs to override
ComplexClass is given a particular
Sortable implementation as a constructor argument.
ComplexAlgorithm does not care what exact sorting algorithm is being used; it is happy that that object implements the
sort() method of
A lot of flexibility results due to the use of the strategy pattern. You can dynamically change the strategy and pass in the right one according to the context.
The observer pattern is a way of notifying a change to a number of classes.
If you are a fan of cricket, you may want to know whenever Sachin Tendulkar scores a century so that you can celebrate.
All such similar people would register themselves to the event of Sachin scoring a century. Each of these people is now an observer for that event. Whenever Sachin does score a century, a centralized program will notify each observer.
Another example is that of online bidding. A group of bidders at an auction register themselves to receive notifications when a higher bid is placed. As soon as a bid higher than the current one is placed, all the registered bidders get to know about it.
There are two main parts to implementing the Observer design pattern.
Here is a simple implementation of the Observer pattern:
We have created an instance of
SachinCenturyNotifier and registered three fans with it.
Whenever Sachin scores a century, the call
notifier.sachinScoredACentury() would be made and all three fans would be notified.
The visitor pattern allows us to add a new operation to a class without changing the class.
There are a lot of scenarios when designing frameworks, where we don’t want other people to modify the code in the framework. We want others to extend the functionality without touching the framework code. They are allowed to add new operations, but not to change the existing operations.
The visitor pattern allows you to do this.
A good real-world example of the visitor pattern is the operation of a taxi company.
As soon as a person calls a taxi company, and a cab is dispatched, the company accepts a visitor. Once the visitor, or customer enters the taxi, he is no longer in control of where he is going. The cab driver is now in control.
If we look at it as object-oriented code, the driver class is in control of the customer class. The driver class can add new operations on top of the customer/visitor.
The template method pattern is used to defer the exact steps of an algorithm to a subclass.
A good real-world example of this pattern is how we go about creating a house plan. Any good house plan consists of a floor plan, the foundation, plumbing, framing, and wiring. Such a plan is almost identical for each house.
If you were to model this in software, you could create a template class with this standard behavior defined. A subclass could extend this and give actual implementations. Such details could include the wooden flooring type, the wall paint colors, and any added wings as required.
A good example of the template method pattern is within the Spring framework, in the form of
handleRequest() merely takes care of the basic things. However, it leaves the lions’ share for the implementation of the method
handleRequestInternal(). This method is defined by subclasses, where more specific logic can be implemented.
The template method pattern is all about doing the high-level steps and leaving the low-level details to the subclasses. The subclasses can override the low steps and provide their own implementation.
The command pattern encapsulates a command request as an object.
Let’s take a real-world example.
Consider the scenario when a customer goes to a restaurant and wants to place an order for a meal. The writer merely writes the order he gets on a piece of paper and passes it on to the chef. The chef executes the order and then prepares the meal. He passes the piece of paper to the manager.
The verbal order from the customer has now become a paper object. This piece of paper is the command object. The command object contains all the details needed to execute the request.
Similarly, in object-oriented programming, we can encapsulate all the details of a request into an object and pass that object to execute it.
In web applications, when a user types in the details on a form, these details are captured in a single request object, which is then passed across.
java.lang.Runnable is also a good example of how this pattern is implemented. We create threads in Java by extending the
Runnable interface, which has all the logic for execution in its
start() method. When we want to create and start a thread, we pass this class to the
The memento pattern captures and later restores an object’s internal state.
A lot of games that we play offer the option of performing an intermediate save. At a certain point in the game, you can save it and later come back to it.
To implement this, we need to save the internal states of the game objects and restore them at a certain point in time.
This save-revert functionality can be implemented by using serialization in a language such as Java.
The memento pattern is very useful in implementing undo/redo operations.
For example, if you are working on a text document in a word processor. If at a certain point, you decide to undo changes, you can see each undo until you reach a point where you are satisfied. You have now reverted to an earlier saved state of the document.
The mediator pattern is used to define simplified communication between classes.
Take the example of an Air Traffic Controller (ATC). Let’s say that at any point of time in India, we have about 500 flights in air. We need to decide the routes that each of these flights needs to take. This also includes deciding the times at which each of these flights takes off and lands. It would be a highly complex situation if each of these 500 flights needs to talk with each other and arrive at an acceptable schedule of routes.
That’s why we have the concept of an ATC. The flights communicate with the ATC, and having assimilated the information from all the flights, the ATC makes the decisions and communicates them back the flights.
In the software world, a good example of the Mediator pattern is the ESB (Enterprise Service Bus). In a distributed system, instead of letting the applications talk to each other, an application drops in a message to the ESB. The ESB routes the request to the application that needs to handle the request. It acts as the Mediator.
In this article, we had a quick look over a variety of design patterns.
A design pattern is an approach to solve a problem in a given context. We focused on understanding the context in which a particular pattern may be applicable to real-world examples.
Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.
The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.
Builder is one of the** Creational Design Pattern**.
Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.
As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters”
#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
If the cost for creating a new object is expensive and costs resources.
#java #design-patterns #code #tutorial #prototype-design-pattern #design pattern
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a _factory method _— either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes — rather than by calling a constructor.
#factory-design-pattern #code #tutorial #design-patterns #java #factory design pattern — java
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
#design-patterns #java #code #composite-design-pattern #tutorial #composite design pattern — java
A famous general is thought to have said, “A good sketch is better than a long speech.” That advice may have come from the battlefield, but it’s applicable in lots of other areas — including data science. “Sketching” out our data by visualizing it using ggplot2 in R is more impactful than simply describing the trends we find.
This is why we visualize data. We visualize data because it’s easier to learn from something that we can see rather than read. And thankfully for data analysts and data scientists who use R, there’s a tidyverse package called ggplot2 that makes data visualization a snap!
In this blog post, we’ll learn how to take some data and produce a visualization using R. To work through it, it’s best if you already have an understanding of R programming syntax, but you don’t need to be an expert or have any prior experience working with ggplot2
#data science tutorials #beginner #ggplot2 #r #r tutorial #r tutorials #rstats #tutorial #tutorials