All things about Singleton design pattern

What is it?

The Singleton pattern is one of most popular design pattern. This design pattern is built based on the regular of only one object instance in whole application.

Why to use it?

We could use singleton pattern when we need to share state, context, caches, or any other data that we want to be unique and same in whole application.

How to use it?

The keyword for this design pattern is “static”, “private constructor”.

Static is initializing object only one time in whole application and the object could be accessed anywhere.

Private constructor is to prevent calling externally constructor many times to make sure to exist only one instance in whole application.

Some issues

The issue we could face when using this design pattern is about concurrency updating to the single instance. The changes may be conflicted each other.

We could think about locking object before updating and unlocking object after updating. But it seems there is no completely perfect solution for it. Locking object may block other actions that need to consume that object.

Category: Design pattern