DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Implementation Best Practices: Microservice API With Spring Boot
  • Requirements, Code, and Tests: How Venn Diagrams Can Explain It All
  • Maven Dependency Scope Applied
  • Exploring Throttling in Java: Simple Implementation Examples - Part 1

Trending

  • Build Your Business App With BPMN 2.0
  • Build an Advanced RAG App: Query Rewriting
  • Next-Gen Lie Detector: Stack Selection
  • Outsmarting Cyber Threats: How Large Language Models Can Revolutionize Email Security

Why Classical Singleton Is an Antipattern: How To Make It Great Again Using IOC

In this article, find out why the Classical Singleton pattern now is recognized as an antipattern and learn how to make it great again using IOC.

By 
Dmitry Egorov user avatar
Dmitry Egorov
DZone Core CORE ·
Updated Feb. 27, 22 · Analysis
Like (10)
Save
Tweet
Share
8.5K Views

Join the DZone community and get the full member experience.

Join For Free

Classical Singleton Introduction

Classical Singleton is one of the most well-known structural patterns. It is widely used in production and is responsible for creating only one single instance. This pattern was mentioned in the GOF patterns book. How is it possible that it became an antipattern? Before we start, let's remember what a classical Singleton looks like.  

Classical Singleton Implementation

Classical implementation of Singleton assumes that class contains two things:

  • Class content and its logic
  • Taking care about only its single instance

Let's take a look at the classical example below. Here you can see eager instance initialization (and it doesn't matter, actually). The private constructor doesn't allow you to create more than one instance. Singleton class is accessible via the getInstance method. All logic and fields related to the class's activity show that the class has its own activity.

Part Responsible for Single Instance/Class's content and logic

Why Is Classical Implementation an Antipattern?

The provided example creates only one single copy of the Singleton class and can be accessed through the getInstance method. However, the most important part of this class is its logic that comes together with some fields and methods. What is particularly wrong with it?  Let's appeal to SOLID principles and try to apply them:

Single Responsibility

Single responsibility means that class should serve only one purpose. In our case, this rule is violated because the implementation class also takes care of single initialization. 

Single Responsibility

Open Close Principle

The Open Close Principle says that a class should be open for extension and closed for modification. This rule is also violated because we can't even extend this class due to private constructor:

Can't extend Singleton Class

Liskov Substitution

The Liskov substitution says that subclass B of class A should be able to be replaced by B without disrupting its design. Obviously, it's violated for the same reason: we can't create subclasses.

Liskov Substitution

Interface Segregation

This principle says that interfaces shouldn't have methods that it doesn't use. Well, Singleton is class and not designed to have any interface wrapper, so this rule is not applicable here.

Interface Segregation

Dependency Inversion

The dependency injection rule says that entities must depend on abstractions, not implementations. The rule is violated because this version of Singleton is based on the concrete implementation.

Dependency Inversion

All SOLID Rules Are Violated

Overall, such Singleton implementation violates all five rules. Therefore, that means that this such design brings many potential development and maintenance problems such as:

  • Slow development and maintenance 
  • Very difficult testing 
  • Poor design

Personally, even I for a long time did not doubt in classical Singleton (but I definitely had issues with testing it). However, after analysis, we see that actually, the old good friend is a wolf in sheep's clothing.

Wolf in sheep's clothing

Inversion of Control (IOC) Based Singleton: Good Alternative

Singleton implementation shown earlier is one of the possible options of creating single instances of a class. There is a better way to do it: use an IOC container. An IOC container takes care of classes and their instances. In the next example, we use a Spring IOC container that creates a Singleton class as a Singleton bean. Scope Singleton shown in the example below is unnecessary because any bean is Singleton by default. 

IOC Container

There are two parts. Class Singleton itself should be moved outside and do its job somewhere else without knowing how it will be initialized, as a single instance or differently. Let's answer the same SOLID questions:

Single Responsibility

IOC makes the initialization part and class itself separately; therefore, the principle is followed.

Open Close Principle, Liskov Substitution, Interface Segregation

As long as the class is not coupled with an IOC container, you can write any class implementation. Therefore, principles can be followed if developers follow these rules.

Dependency Inversion

It depends on the IOC container. Spring allows flexibility and any bean defined in context can be an interface. Therefore, if developers make designs based on abstraction (e.g., interface) then the rule is followed.

Spring IOC Is Not Only an IOC Container

You might have an impression that Spring is the only IOC container. However, IOC is just a pattern and can be created on your own. You can also use alternatives like Google Guice which is pretty lightweight. 

Instead of Conclusion

This topic might raise discussion, so any comments and ideas are welcomed.

Implementation

Opinions expressed by DZone contributors are their own.

Related

  • Implementation Best Practices: Microservice API With Spring Boot
  • Requirements, Code, and Tests: How Venn Diagrams Can Explain It All
  • Maven Dependency Scope Applied
  • Exploring Throttling in Java: Simple Implementation Examples - Part 1

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: