What is Singleton Design Pattern?
Tags: java, webdev, javascript, productivity
Published: 2020-04-16 08:38:07

Hey there, programming buddies! You surely must have heard about “Design Patterns” quite a many time in your programming journey! The concept of Design Patterns has not been with us for ages and the concrete idea was articulated somewhat 20-30 years ago in the mid-nineties. That surely was not long ago as time is flying pretty quickly and we need things to be done efficiently so that we can have our codes maintainable, extensible and reusable. Design Patterns or more specifically Software Design Patterns, help in doing that. There are different design patterns and we will be introducing you to Singleton Design Pattern, which is a simple one and easy to follow, among all others.

But first things first – We will introduce what design patterns are, their advantages, a bit of history and only then get started with singleton design pattern. Don’t you worry, there will be code examples too and if you are not familiar with Java, we will refresh some of the Object-Oriented Programming principles as well.

##[What is the design pattern?](https://www.decipherzone.com/blog-detail/singleton-design-pattern-java)

You can think of design pattern as an idea, a way of structuring your code so that you can create a reusable, maintainable and extensible software. It is not a programming language nor it is a library, just concepts with which you can write flexible code with. More formally, design pattern is a standardized way to address a recurring problem. Problems that were faced by lots of developers over a long time. Problems that put them in a loop hole i.e. made them modify classes or parts of their code completely for making minor changes. Software development is equal to solving problems and the articulation of these ideas began with a book in the mid-90s, Design Patterns: Elements of Reusable Object Oriented Software. The authors of this book are known as the gang of four. If you have ever used any library or framework, you have already made use of design patterns without having to implement one for your own code.

##[Why do we need design patterns?](https://www.decipherzone.com/blog-detail/singleton-design-pattern-java)

There is a common misconception that if you know the basic principle of Object-Oriented Programming like encapsulation, inheritance, abstraction, polymorphism then that makes you a good OO designer. Even if you are trying to make a simple calculator app in a programming language like java, swift or c#, you indeed are making use of the Object Oriented principles but there is no guarantee that your code can incorporate changes easily without having to make major changes to your classes. On industry scale, such issues were and are still common and therefore developers have adopted the ideas of following a design pattern. Design patterns do not give us code, they give general solutions to software design problems.

##Benefits of using design patterns at a basic level

Using design patterns make you a better designer, you can come up with you own design pattern if the classic ones are of no use to your specific problem.

We have mentioned this time and again, you can create reusable, maintainable and extensible software

It will also help you learn new frameworks and libraries quickly because the best ones out there make use of these ideas.

Lastly, we will make use of an analogy to help you understand the significance of using design patterns. In software engineering, the term coupling is quite ubiquitous, it determines the degree of interdependence between software modules. Think of your car, you are stranded in middle of nowhere with a flat tyre. The “design” of your system (car) is such that you don’t have to pull out your engine or steering wheel or any other part of your car to replace the tyre. You can simply replace it with a spare one. Your car is an example of loosely coupled system i.e. the components of your car work together but are not highly dependent on each other. You do not need to do something with your tyres to start the engine. See, how effective a design pattern can be in any walk of your life, it is not just applicable to software.

##What are the available design patterns we can make use of?

Officially, as per the Design Patterns: Elements of Reusable Object-Oriented Software book we have 23 classic design patterns. They have been categorised into 3 types:

Creational - Design patterns that fall in this category are all about different ways of creating objects.

Structural - Structural design patterns are about the relationships between the objects.

Behavioural – Behavioural design patterns define the interactions or communication between objects.

**Article Source: https://www.decipherzone.com/blog-detail/singleton-design-pattern-java**

Thera are obviously other design patterns as well that solve specific design problems, you can come up with your own or maybe you have been using one for a long time without knowing it. Well, maybe now you know! Modern languages nowadays have built in support for design patterns i.e. they might have some pattern that you must follow in order to maintain the basic design principles.

Next up, Singleton Design Pattern. What category of design pattern does Singleton Design Pattern fall in? (Hint: only one instance of class is created) We will discuss that in a bit, first we will cover some basics of Java so that you can understand the code examples better.

"[Top 5 Best Free Java Development IDE in 2020](https://www.decipherzone.com/blog-detail/best-free-java-development-ide)"

"[Java vs. JavaScript: Know The Difference](https://www.decipherzone.com/blog-detail/java-vs-javascript)"

"[The RoadMap for Java Developers in 2020](https://www.decipherzone.com/blog-detail/roadmap-java-developers-2020)"

"[Java vs Python: Which One is Better for Future?](https://www.decipherzone.com/blog-detail/java-vs-python-which-better-web-app-development)"

"[Top Best Tools For Java Developers In 2020](https://www.decipherzone.com/blog-detail/best-java-development-tools)"

"[Top Java Frameworks for 2020](https://www.decipherzone.com/blog-detail/top-java-frameworks)"

Before diving in to singleton design pattern in java example let’s discuss some of the necessary Object-Oriented Programming concepts

###Classes

Classes in Java are similar to what you have used in C#, Swift or C++.If you do not know what a class is you need to take a class on OOP, my friend. For a refresher, class is a blue print of an object, it contains implementation behaviour of that object.

In Java a class is defined using the class keyword. Take a look at an example below. The class defines a user and has the name variable and User constructor for instantiating the user variable, sayHello() is a method that simply prints the name.

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern.png)

In order to instantiate this class, you will have to use a new keyword in the main method. Take a look at the snippet below.

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern1.png)

###Interface

Interface is one of the most misunderstood constructs in java. In simple words, it is a kind of contract that specifies the capabilities that a class should provide. The image below perfectly demonstrates the role of an interface. Imagine you want to open a restaurant, you need a chef, it does not matter who the chef is, the only thing that matter is that the person can perform the role of a chef. If John does not have prior chef experience, he/ she can implement the guidelines from the chef booklet (interface), same applies to Mary.

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern2.png)

###Declaring an interface:

Just like a class, we have used the interface keyword here. Note: we just have a method declaration in the snippet below.

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern3.png)

If you want to build a tax calculator class that using this interface then that class should have a method with the signature defined in the interface. See, the next snippet.

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern4.png)

You can also extend it to other classes i.e. “reuse the interface”, sounds like a design pattern huh?

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern5.png)

Next, thing is to use the implementation inside the main class.

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern6.png)

The benefit of using interface they function to break up the complex designs and clear the dependencies between objects. They make the application loosely couples, one of the goals of using a design pattern.

###Encapsulation

Encapsulation is the bundling of the data and methods that operate on the data in one class and also hiding the values and state of an object within that class. Take a close look at the snippet below, the methods and the data have been bundled inside one class, this is an example of encapsulation. Also, of you are curious the keyword private keeps the variable balance to the class itself i.e. it is not inherited by the subclasses.

![What is Singleton Design Pattern?](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern7.png)

###Abstraction

Abstraction can be defined as the idea of reducing complexity by hiding unnecessary details from the user. You can think of a tv’s remote control, it has a bunch of buttons and  transistors inside its circuit- we don’t worry about how they work under the hood, we simply use the device , this is the abstraction principle.

We won’t discuss polymorphism and inheritance in much detail because these examples should suffice to make you understand the Singleton Design Pattern, the reason to stick these in were to make you familiar with Java syntax.

##[What is Singleton Design Pattern?](https://www.decipherzone.com/blog-detail/singleton-design-pattern-java)

Singleton design pattern is a software design pattern for objects that restricts the instantiation of a class to one "single" instance. It is a creational design pattern which is extremely useful when exactly one object is required to coordinate actions across the system.

Finally, we are now ready to deliver you your first ever classic design pattern example. But before that we need to answer a question. Why does Singleton Design Pattern fall in to the category of Creational Design Pattern? The reason is because it deals with creating an object and that too only once. Wait, what kind of thing is that? Instantiates only once? Allow me to explain it in detail, a singleton design pattern has two basic properties:

You should create the class in such a way that it produces only one instance of itself.

The instance of that singleton class should be accessible globally.

What is the significance of doing that? We will answer that in a bit but first let’s see how can we create such a class.

Take a look at the following singleton design pattern in java example:

![What is Singleton Design Pattern](https://ares.decipherzone.com/blog-manager/uploads/ckeditor_Singleton%20Design%20Pattern8.png)

By following this approach your class will always return a singleton object. If you are wondering, static keyword allows you to access the members of that class without having to instantiate them.

We know what your next thought might be. If that is what static means then the Singleton Design Pattern’s whole principle falls into place, we do not need to instantiate the object, cannot we just use a global variable instead of doing this painful task?

Good thoughts! But have a close look, they are private variables too, so only the class can access it. For your second question, why not use a global variable? Global variables can cause some problems, if they are resource intensive and maybe your application does not use it at all, they also may cause namespace issues, naming conflicts. The point is Singleton Design Pattern follows an approach that allows you to make use of that object only when you need it (lazy instantiation). Using singleton objects solves the problem of polluting the namespace as well. The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

Let’s get back to understanding that snippet, notice that the constructor of the singleton class is declared private that means only the class itself can instantiate. The getInstance method makes sure that if the instance of “isalwaysSingle” class is created only once and returns it whenever asked for it.

What did we learn from this singleton design pattern example?
The Singleton design pattern ensures you have at most one instance of a class in your application.

The Singleton design Pattern also provides a global access point to that instance. Having one instance of a class makes your application more resource efficient. You do not have to create multiple objects every time to accomplish a task, simply grab that object anywhere and use it.

##Where’s the use of Singleton Design Pattern?

If you are trying to create an application that needs to cache some data, you can use singleton object for that. Other examples include device drivers for printers to avoid multiple concurrent access to the resources and prevent deadlocks.

Your aim should be to aware yourself of the classic design patterns, knowing those design patterns will automatically benefit you in writing code efficiently. We hope, you got to learn something valuable out of this blog!

"[Top Best Web Development IDE in 2020](https://www.decipherzone.com/blog-detail/best-web-development-ide)"

"[Artificial Intelligence is the Future of Web Development](https://www.decipherzone.com/blog-detail/future-of-web-development)"

"[Modern Web Development, Design and Deployment](https://www.decipherzone.com/blog-detail/modern-web-development)"

"[Top 10 Backend Frameworks for Web Development in 2020](https://www.decipherzone.com/blog-detail/top-10-best-backend-frameworks-for-web-development-in-2020)"

"[Top 10 Web Development Trends That will be in Demand in 2020](https://www.decipherzone.com/blog-detail/top-10-web-development-trends-in-2020)"

"[How to Improve Your Programming Skills?](https://www.decipherzone.com/blog-detail/how-improve-programming-skills)"

**Article Source: https://www.decipherzone.com/blog-detail/singleton-design-pattern-java**