Activity 15-1 Singleton Pattern

(video segments from “Pile’o patterns”) ## The need for a single instance

Single instances can be used to allow an application to provide services, and have different components of your application access those services.

Example: We could be setting up the gateway in our applications thus (we’ll talk about the “instance” part):

ServiceLocator.getInstance().registerService("ProfileGateway", new MySQLGateway());
// ...
// much much later on ... in our interactors
// We need to do a downcast
ProfileGateway g = (ProfileGateway) ServiceLocator.getInstance().getService("ProfileGateway");

In order for this to work effectively, we must make sure that the code that adds the services and the code that uses the services are both referencing the same instance of ServiceLocator.

We have effectively three ways to address this:

The singleton pattern

Code at handout

Code at handout

Monostate

Monostate prevents users of knowing that they are using a static variable.

Monostate uses static fields and non-static methods operating on those static fields. All methods operate on the same fields.

Null Object Pattern

How to handle returns from methods that “may fail”.