Design Patterns Part I: The Singleton Design Pattern

Singleton Design Pattern

Singleton Design PatternIntroduction

Possible Questions

  • Tell me a bit about design patterns
  • What is good about design patterns?

Design Patterns are another oft used area during interviews.  Originally pioneered by the “Gang of Four” (GoF) in one of the more dry textbooks you’ll read in your life Design Patterns: Elements of Reusable Object-Oriented Software. A design pattern is a way of structuring or shaping the design of your code which is well tested and proven. You cannot “invent” a design pattern and call it a design pattern.   A design pattern establishes itself over time.

Importantly, they (normally) work across languages, particularly OO.  The GoF book was written in C++ but the ideals apply equally to C# and Java.  The reason why Design Patterns are so brilliant are that they provide a common language between developers. If you wanted to created a singleton (more on that shortly) then as opposed to having to explain to the other developer what one is, how it would be implemented etc., design patterns mean you can say “this should be a singleton” and everyone understands what you mean.

Design patterns are an important toolkit to building systems.

Singletons

A Singleton is used when you want a single instance of an object in your entire application. You want to literally remove the ability to create multiple instances of something.  This can be useful for things like data storage, where you want a single go-to place in your application to get data on something.  The singleton pattern governs the creation and access of an object in order to create this restriction.

Possible Questions:

  • How do you create a Singleton in Java?

Objects are created using constructors. In order to be create the restriction you need to remove this ability. This can be done in Java using a private constructor.  This means that only static methods in the class itself can create the object.  An accessor method is then provided which makes the single instance of the object available.

public class SingletonExample {
    private static SingletonExample singleton;

    private SingletonExample(){ //Hides constructor from public view
            
    }
    
    public static SingletonExample getInstance(){
        if(singleton==null){
            singleton = new SingletonExample();
        }
        return singleton;
    }
}

 

This now means that anything trying to access SingletonExample will have to go through our getInstance method().

Possible Questions:

  • How do you cope with thread safety when creating a Singleton?
  • What is the difference between lazy and eager instantiation? Why does it matter?

Due to the lazy instantiation, that is, the fact the object is not created until it is first needed, the code sample above is not threadsafe. If multiple threads try to simultaneously access the Singleton it can result in 2 objects getting created, thus defeating the purpose of the pattern.  There are two ways around this:

  1. Make the getInstance() block synchronized.  This ensures that only one thread can access the method at once.  This however will make all calls to getInstance() syncronized which could result in performance degredation
  2. Use Eager Initialisation.  By initialising on the field the object is guaranteed to be ready before access, eliminating threading and performance issues.
public class SingletonExample {
    private static SingletonExample singleton =  new SingletonExample();;

    private SingletonExample(){ //Hides constructor from public view

    }

    public static  synchronized SingletonExample getInstance(){
        return singleton;
    }
}

But when do you choose between lazy and eager initialisation?  Lazy initialisation defers creation of an object until you absolutely need it. If it’s an “expensive” object like a database connection for example, it could in theory be good to use lazy initialisation if there’s a chance the connection won’t be needed.   However, the benefit of lazy is simply that you will speed up your start up time.  If startup times are not a concern for you (and generally they aren’t), go with eager initialisation as it solves a lot of problems with threading.  The simple fact is Threading is hard and if you can avoid things like syncronized then the trade off is worth it.

Possible Questions

  • Are singletons a good pattern to use?
  • How do singletons affect testing?

Singletons are not a good coding practice as they cause high coupling and violate dependency injection principles.  This makes code really hard to test.  Any object making use of a singleton needs to use a static method to get access to it.  This means it is not being “injected” in and so cannot be stubbed out for use in testing.  This can cause real problems as Singletons are often used to manage resources.

 private final SingletonExample instance;

 public ThingThatUsesSingleton(){
    instance = SingletonExample.getInstance();

 }
 public int doSomethingThatICanUnitTest(){
    instance.doSomething();
    return 17;
 }

In the above example I want to unit test the doSomethingThatICanUnitTest() method to ensure it returns 17. However, when I try to create this class in my test it will force the creation of a SingletonExample object and any expense that it has.  If it’s a database connection for example, that means my unit test will try and connect to the database as part of my unit test which is terrible.  Dependencies should be injected in so that I can mock them out and test the behaviour I actually care about.  Singletons break this.  As a result they are often avoided in reality, although they are the most well known pattern and so are often used as an interview question.

 

What do you think? Have you had these questions in an interview before? Why not put a comment below and let us know your experience.

If you’d like more questions like this into your inbox then sign up for the mailing list below!

[mc4wp_form]

One Comment

  • In my interview, the interviewer also mentioned that Singleton may lead to memory release in Java.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>