O'Reilly logo

Swift 2 Design Patterns by Julien Lange

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The singleton pattern

This pattern is certainly the pattern that every developer learns first. It is often used with a factory or abstract factory class to ensure that there is only one instance of the class.

Roles

The singleton pattern ensures that a class has only one instance and provides a global point of access to it, and at this point, it returns an instance of this class.

In some cases, it can be useful to have some classes that have only one instance; for example, in the case of the abstract factory, where it is not useful to have several instances.

Design

The following figure shows the generic UML class diagram of the singleton pattern. There are many way to write the singleton pattern using Swift.

Here, we use the easiest way to do this. With ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required