OOP Design Patterns: Singleton

Patroclos Lemoniatis
1 min readFeb 13, 2021

As a Creational Pattern, Singleton is used to create one instance of a class.

Instead of creating multiple instances of a class whenever is needed, the class is instantiated once and used as a static resource.

Implementation

One class is created TestSingleton, having private constructor, a private static field instance and a public getInstance method. Other classes can access the instance from calling the getInstance method.

public class TestSingleton {   private static TestSingleton instance;   private TestSingleton() {}   public static TestSingleton getInstance()
{
if (instance == null)
{
instance = new TestSingleton();
}
return instance;
}
}

Running the code will give use the following …

public class TestSingletonMain {   public static void main(String[] args) 
{
TestSingleton singletonInstance = TestSingleton.getInstance();
System.out.println(singletonInstance.hashCode());
singletonInstance = TestSingleton.getInstance();
System.out.println(singletonInstance.hashCode());
}
}

Output

1554547125

1554547125

Interestingly, one instance of the class is created as it is shown from the same hashcode generated. So instead of having multiple instances filling the memory, we are sure to get only one which is reused when needed.

Considerations

  • Singleton pattern is considered an ‘anti-pattern’ as it does not allow to be inherited from another class.
  • Violates single-responsibility-principle, by controlling their own lifecycle
  • It does not allow Test-Driven development as no new instances can be created for each test.

--

--