740-206-9624

Blog

Design Patterns – Singleton, pattern or anti pattern?

Sep 5, 2019 | Design | , , , , , | 0 comments

 

Introduction

Patterns are interesting to me.  You can observe patterns almost wherever you look.  Where you see a repeated pattern it seems obvious that some sort of thinking has gone into what you’re observing.  Patterns imply design and design implies a designer.  As a Christian this has great meaning for me because the design that is observed in creation such as the Fibonacci sequence points to a designer that had purpose in the way this world was made.  This is much like software design.  A good software solution always results from a very intentional and skilled software engineer thinking about the way the software should be written and then building the solution accordingly.  Software solutions do not just happen, a designer must make choices and follow best practices to build something that solves the problem that is being addressed.

 

What are Design Patterns?

Software Design Patterns are constructs in Software Design that represent a repeatable and proven approach to solving common problems in building software solutions.  They really only apply to solutions built with Object Oriented Programming languages such as Java or Smalltalk.  The Gang of Four Design Patterns book was first published in 1994, copyrighted in 1995 and it began as an informal session at OOPSLA ’90, an annual ACM research conference.  The session was run by Bruce Anderson whom I much later had the privilege of working with during my time at IBM, although it is unlikely that he remembers me today.  The Design Patterns book is the defacto reference manual for design patterns to this day although not without some controversy.   Paul Graham a major proponent of Lisp and Arc has the following to say about design patterns:

“When I see patterns in my programs, I consider it a sign of trouble. The shape of a program should reflect only the problem it needs to solve. Any other regularity in the code is a sign, to me at least, that I’m using abstractions that aren’t powerful enough– often that I’m generating by hand the expansions of some macro that I need to write.” – Paul Graham, Revenge of the Nerds

Even the original authors of the GoF Design Pattern book indicated that they would have changed a few things if they were to write the book again.  Particularly that they would have recategorized some patterns, added a few new ones and removed the Singleton pattern altogether!

I am planning on doing a series of posts on design patterns and thought why not start with the most controversial pattern of them all the Singleton design pattern.  Before we get into why people don’t like the Singleton, I think it would make sense to provide a brief explanation of what the actual pattern is.

 

Singleton Explained

The Design Pattern book indicates that the intent of the singleton pattern is to “Ensure a class only has one instance, and provide a global point of access to it.”  The go on to use the example of a printer spooler as a design case for the singleton pattern.  They also mention a file system and a window manager as other possible applications for this pattern.  The Design Pattern book indicates that the Singleton pattern is best used by an Abstract Factory class to create single instances of corresponding Factory classes or to create a single instance of a Facade class which acts as a unified interface to a complex sub systems functionality.

The way that a singleton pattern is implemented is actually quite interesting from a software engineering standpoint.  Essentially the pattern functions by making the constructor private and instead exposing a public static method that returns an instance of the singleton while ensuring that the constructor is only ever called once.  Here is a UML sketch to show what this looks like.

There are two other key things to note when discussing the implementation of a Singleton design pattern.  First there is a private static property in the singleton class that holds the instance.  Second, the method used to retrieve an instance of the singleton checks to see if the private static instance property is populated or null.  If it’s null, than it calls the Singleton constructor whereas if it’s populated then it skips calling the constructor and just returns that instance to whomever is asking for it.  The following is an example Java implementation of a Singleton Class:


/**
 * An example of one way to implement the classic
 * Singleton Design Pattern in Java
 * 
 * @author: Brad Jones
 */
class Singleton
{
    // static variable instance Singleton
    private static Singleton instance = null;
    private String state = null;
   
    // private constructor only available within this class
    private Singleton(){
        state = "initialized";

    }
 
    // static method to return instance of singleton
    public static Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        } 
        return instance;
    }
   
    //Method that can be called on the instance    
    public String getState(){
        return state;
    }
}

Pattern or Anti-Pattern?

So now that we understand exactly what a Singleton Pattern is, let’s talk a little bit about whether or not it’s ever a good idea to use a Singleton in software that you are writing.  There are varying opinions on this matter, I fall in the camp that thinks it’s a bad idea to use a singleton in pretty much any part of your solution.  I have a number of reasons for taking this position.  The pattern is actually flawed from the start in the following ways:

First, it promotes the use of global state which, if you’re a programmer, you know that this is a very bad idea because it leads to difficulty in a lot of areas, particularly testing and maintenance.  Anytime you declare a variable as static, particularly when talking about Java that variable is bound to the JVM rather than the application and becomes except from things such as garbage collection, etc…  Because of the global access it gives to the singleton instance it also functions as an anti dependency injection pattern which is one way that it contributes to difficult testing and maintenance.  Even the Design Pattern book states that the pattern is designed to provide a global point of access to the single instance it creates. 

Second, it can hinder the scalability of your application in a number of ways.  Let me say that there is no problem with only having once instance of an object.  The problem comes when you say that you can only ever have one instance of an object.  What I mean is that it becomes a problem when you programmatically enforce this.  The reality is that, even though it may seem like you would only ever need one instance of an object it is likely that as the application grows you’ll come to realize that you might need more than one instance.  If you programmatically enforce a single instance than you’re application is stunted from growing.  Also, singleton’s can become a bottleneck, particularly in multi-threaded applications.  I was on a project once that had implemented the factory pattern for database connections and used a singleton for the factory object.  This resulted in a bottleneck that caused major performance problems because the application could not get access to the database in a timely manner through the single instance database connection factory.

Third, and finally, the singleton pattern violates the Single Responsibility Principle of computer programming that promotes that every method, class, function, etc… should encapsulate and have responsibility of a single part of the solution.  But, a class implemented with the Singleton pattern has two responsibilities, first it manages the single instance of the class and second it performs whatever function the class is designed to do such as with a factor class, creating an instance of classes to be used by the application.

Conclusion

The Singleton pattern is an interesting one because of the way that it takes advantage of a private constructor but it does not offer any benefit to the designer and results ultimately in more headache than help.  I have seen first hand how it can cause issues in your application and I would not recommend that it be used, particularly as a standard part of your software engineering toolbox.  Now I’m not going to say that there is never a time that it can be used but I will say that it is very unlikely.  I also find it very interesting  that the GoF authors indicated that the Singleton pattern is the single pattern they would remove from their book if they were to do it again and I think it’s because they realized some if not more issues with the pattern as we’ve discussed in this post.

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *