Alternatives to Singleton

Programmers generally don’t recommend using the singleton pattern because we can only create one object due to its design. Let’s discuss its advantages and disadvantages in detail.

Advantages

  • Singleton prevents other objects from instantiating the copies of the singleton object, ensuring that all objects access the single instance.

  • The class controls the instantiation process. So, it has the flexibility to change the instantiation process.

  • We don’t need to include multiple variables in this method, so its implementation is quick and easy.

Disadvantages

  • In programming, global variables are generally considered bad because any code in the application can make changes to it. The singleton pattern violates this principle.

  • The one object creation principle makes it difficult for the system to scale. We need to be 100 percent sure (which is generally not possible) that we only need one instance during the whole lifetime of the class.

  • The singleton pattern makes unit testing very difficult. In unit testing, we generally want to mock the object, and the singleton pattern doesn’t allow that.

  • The singleton design pattern doesn’t support inheritance.

  • One object can become a bottleneck in parallelizing the code because an object must be serialized to access the singleton in a multithreaded system.

Limitation

Suppose that we’re implementing a web server as a singleton. It will eventually peak when we get too much traffic. Since we’re using a singleton, we couldn’t scale the number of server objects. We should be very cautious before using the singleton pattern. The solution to the above problem is to use the monostate pattern.

Monostate pattern (Borg idiom)

The monostate pattern can be used as an alternative to the singleton design pattern. As the name suggests, it will have a single state. This means that all instances of the class will share the same state of the class (data members).

A monostate is a conceptual singleton. All the data members of a monostate are static, so all instances of the monostate use the same (static) data. We can create as many instances as we want, but all will share the same state.

Example

Get hands-on with 1400+ tech skills courses.