Member-only story
One Situation When Reusing Object Instance / Singleton Won’t Work in Java
I remember that I once had a discussion with a coworker who encouraged our team to adopt a singleton pattern, preferably through Spring. Back then, I did not understand the singleton at all, and I clearly did not see the reason why I would use it. So, I said something like “a singleton pattern does not work for all cases” without really knowing what I am talking about. He answered me back saying “why not? Give me an example where a singleton won’t work.” I did not know how to answer, but I definitely found a case where a singleton or an reusing Java instance won’t work.
Consider a POJO or a Java domain class. And you want to create the list out of it. Let’s say we are using ArrayList for this…
1
List list = new
ArrayList();
Now, let’s say we also have a POJO class called Product. Here is how we will normally create a list of Product.
List list = new
ArrayList();
Product product1 = new
Product();
product1.setName("Apple Watch");
// Set more fields in product1
Product product2 = new
Product();
product2.setName("Google Nexus");
// Set more fields in product2
list.add(product1);
list.add(product2);