Quantcast
Channel: Alexandru V. Simonescu
Viewing all articles
Browse latest Browse all 17

Singleton design pattern

$
0
0

The article you’re about to read is part of a bigger series about software design patterns implemented on languages using the JVM, mostly Java. In this one the Singleton pattern is presented.

Table of contents

Description

Sometimes in our applications we need a only one instance of an class. Mostly all the time, that class instance is being created when the application starts up and disposed when the program ends. Having more than one instances for this classes results in a logic failure

Such objects are sometimes factories, for example an factory being in charge of returning always objects from the same pool resources. In this case we need an singleton, either for the pool objects or the factory.

Use cases

There are times when you need to keep a global state in your app, most of the times this ends up being a code smell. A real life example is the Logging, in a application we need to always write to the same logging file, sure we can create the logger instance every time we need it, but the logging functionality is suposed to be used from lots of parts of your application. That means, that file can be opened and written from multiple instances at same time, this will lead to concurrency issues and possible data loss. For this use case we’ll need an singleton, in fact a thread safe singleton.

Pros

  • Applicable to any class. You can apply this pattern to any class just by simply making his constructor private and adding the proper static instance and method.
  • Can be created through derivation. Given a class, a singleton subclass can be created.
  • Lazy evaluation. If the singleton is never used, it is never created.

Cons

  • Destruction undefined. We can never be sure when the static instance gets destroyed. We can add something like a destroy() static method to the class but there may be some other parts of the software that accesses the singleton. With a lazy evaluation approach, it won’t result into any crashes but we will have two different instances of the same singleton.
  • Cannot be inherited. A class derived from a singleton is not a singleton, it needs the static methods and instance variable.

Implementation

A very basic test specification for this patterns can be the following tests:

public class MySingletonShould {

  @Test
  public void always_return_same_instance() throws Exception {
    MySingleton instance1 = MySingleton.getInstance();
    MySingleton instance2 = MySingleton.getInstance();

    assertThat(instance1, is(sameInstance(instance2)));
  }

  @Test
  public void not_have_public_constructor() throws Exception {
    Constructor constructor = MySingleton.class.getDeclaredConstructor();

    assertFalse(constructor.isAccessible());
  }
}

We want our constructor private, as we don’t want users of our API instantiate the class by themselves; and the static getInstance() method should always return the same instance.

public class MySingleton {

  private static MySingleton INSTANCE = null;

  private MySingleton() {
  }

  public static MySingleton getInstance() {
    if (INSTANCE == null) {
      INSTANCE = new MySingleton();
    }
    return INSTANCE;
  }
}

All the code from this post can be downloaded from the Design Patterns repository.

Bibliography


Viewing all articles
Browse latest Browse all 17

Trending Articles