Yes, Singleton Can Be Better

Source: Unsplash

Recently, at my University, I was listening to subject Design patterns where they forced us to use design patterns while making our homework and projects. I was using Singleton pattern as standard implementation where I defined types that I wanted to use, but then I saw an interesting implementation from one guy. As a software enthusiast I always try to find better ways to make some piece of code more effective so I started to use his approach.

“In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.” according to Wikipedia. There are some discussions how Singleton is bad and have nickname “ant-pattern” but I will not enter that discussion in this article, I will just show this approach. In this approach we will define just Hashmap that will have Object as second parameter,with this way we can put any object that we need without worry to define new variable in our singleton class.

Implementation

First we need to create a class Registry and define protected constructor.

public class Registry { 
  private static volatile Registry instance = null; 

protected Registry() {
}
  public static Registry getInstance() { 
if (instance == null) {
instance = new Registry();
}
return instance;
}
}

As I said before, we will not define every variable, we will have just one that will be HashMap, so we will add that in our Registry class and put initialization in our constructor.

private final HashMap<String, Object> items; 
protected Registry() { 
items=new HashMap<>();
}

Also, we need to have setters and getters for our data in Singleton, we will do that through these two methods.

public void set(String key, Object value) {
this.items.put(key, value);
}
public Object get(String key) { 
return this.items.get(key);
}

You should use it in this way

Registry.getInstance().set("model.cat", new Cat("Lion", 1)); 
Object object=Registry.getInstance().get("model.cat"); 
if(object instanceof Cat){  
System.out.println(((Cat)object).getName());
}

That’s it, we are done, we have our Singleton and we can start working with it! Also, full source code is released at my Github profile. If you are interested in full implementation (example included) check it RegistryExample


Originally published at itworkslocal.ly on January 31, 2016.