So, Singleton or Monostate?

Continuing with the design pattern fun, lets talk about one of the most commonly used pattern, Singleton and an alternative called Monostate. I too wrote about singleton pattern relative to Joshua Bloch’s Effective Java a few days back.

The Basic Difference in Two
Well what is this monostate we talk about? Monostate is very similar to a singleton and you may call it a conceptual singleton. The basic difference between the two is that-

Problem with Singleton –
The intent is to ensure that only a single instance of an entity is created, which in turn ensures a single state of that entity which can be shared across threads. But, sharing the only instance we have brings synchronization into picture. Now we have a problem, is there a way to stay away from synchronization as our only instance may have been used extensively?

How Monostate overcomes this problem- Monostate overcomes this problem by simply allowing more than one instances to be created, while maintaining a single state. Confused? Have a look at the following snippet.

Singleton’s constructor is private to prevent explicit object creation. Since, in monostate we want to allow object creation for two threads, we want more than one instance. One for each thread. Thus, we make the constructor public.

Setters and getters remain the same, as they are the ones which update and fetch the state.

Is this totally thread safe? No it isn’t.

Not thread safe? So, why should one use it?

Is not completely thread safe. But, it of course reduces the synchronization issues.

Scenario where it could be useful- In stock market, there are several factors which may affect the performance of a company. Certain global factors which affect the performance should have an atomic state and also must be shared across the various events happening in the share market. So, the state of these global factors must be a monostate.

Deletion of the instances will not result in deletion of the state.

One wouldn’t subclass a singleton. But monostate can be easily sub-classed and behavior can be overriden.

The only bad thing I can think of about monostate is that it consists of creation and deletion of objects, which no doubt are expensive operations.

But, one should be careful when selecting between the two. Ask yourself the question, ‘Do I need a single instance or single state?’