Book Image

Design Patterns and Best Practices in Java

By : Kamalmeet Singh, Adrian Ianculescu, Lucian-Paul Torje
Book Image

Design Patterns and Best Practices in Java

By: Kamalmeet Singh, Adrian Ianculescu, Lucian-Paul Torje

Overview of this book

Having a knowledge of design patterns enables you, as a developer, to improve your code base, promote code reuse, and make the architecture more robust. As languages evolve, new features take time to fully understand before they are adopted en masse. The mission of this book is to ease the adoption of the latest trends and provide good practices for programmers. We focus on showing you the practical aspects of smarter coding in Java. We'll start off by going over object-oriented (OOP) and functional programming (FP) paradigms, moving on to describe the most frequently used design patterns in their classical format and explain how Java’s functional programming features are changing them. You will learn to enhance implementations by mixing OOP and FP, and finally get to know about the reactive programming model, where FP and OOP are used in conjunction with a view to writing better code. Gradually, the book will show you the latest trends in architecture, moving from MVC to microservices and serverless architecture. We will finish off by highlighting the new Java features and best practices. By the end of the book, you will be able to efficiently address common problems faced while developing applications and be comfortable working on scalable and maintainable projects of any size.
Table of Contents (15 chapters)
Title Page
Packt Upsell
Contributors
Preface
Index

Singleton pattern


The singleton pattern is probably the most widely used design pattern since the inception of Java. It is a simple pattern, easy to understand and to use. Sometimes it is used in excess, and in scenarios where it is not required. In such cases, the disadvantages of using it outweigh the advantages it brings. For this reason, the singleton is sometimes considered an anti-pattern. However, there are many scenarios where singletons are necessary.

As its name suggests, the singleton pattern is used to ensure that only a single instance of an object can be created. In addition to that, it also provides global access to that instance. The implementation of a singleton pattern is described in the following class diagram:

The implementation of the singleton pattern is very simple and consists of a single class. To ensure that the singleton instance is unique, all singleton constructors should be made private. Global access is done through a static method that can be globally accessed...