Singletons

Problem

A critical object such as a message broker (i.e., a virtual post office) needs to be shared by multiple correspondents.

Multiple message brokers creates confusion because correspondents need to check several places for their messages.

Solution

There are two solutions:

Make the message broker a utility class with private constructors.

Make the message broker a singleton class (which also has private constructors).

Having private constructors means that correspondents can't construct new instances of the broker.

In the case of the utility class the put and get methods are static, hence no instances are needed.

In the case of the singleton, a static method is provided that insures at most one instance can be created.

Implementation

See

MessageBroker.java

Disadvantages

Much has been written on the disadvantages of the Singleton Pattern including claims that it is evil (but without explanation).

Both Singleton and Utility run counter to the idea of pure object-oriented programming in that they provide a global access point for a set of related services.

Global services are shared by many objects. Like any shared object, they should be thread safe to prevent synchronization errors.

Remember that static fields are initialized at program start up time. In the utility version of the broker this means that the messages map will be created at the start of the program.

By contrast, the messages map of the Singleton broker is only created when makeMessageBroker is first called. In other words, when there is an actual demand for it.

References

Singleton

Synchronization