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…

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);

If you print out the result, you will see something like this:

Apple Watch

Google Nexus

But let’s say you are just reusing the object again.

List list = new ArrayList();

Product product = new Product();
product.setName("Apple Watch");

list.add(product);

// Set more fields in product and reuse for next item
product.setName("Google Nexus");

// Set more fields in product
list.add(product);

If you print out the result, you will see something like this:

Google Nexus

Google Nexus

And this is clearly not what you want. Same thing happens for Singleton. So, for domain class or something that needs to have the unique instance of each like the list of objects, a singleton or reusing object instance does not work.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s