Singleton Design Pattern

Rashad Shirizada
CodeX
Published in
4 min readMay 27, 2022

--

Singleton is a creational design pattern that assures that only one object of its kind exists and gives other code a single point of access to it.

Source: https://treewebsolutions.com/articles/the-singleton-pattern-in-php-65

The singleton pattern is used to produce a single instance of a class, as the name implies. There are a few situations where just one instance of a class should exist and the constraint should be enforced. Caches, thread pools, and registries are just a few examples of objects that should have just one instance.

It’s simple to generate a new object of a class, but how can we assure that only one object is created at any one time? The solution is to make the constructor of the class we want to declare as a singleton private. Only members of the class, and no one else, can access the private constructor in this fashion.

The Singleton pattern ensures that only a single instance of a class exists and that there is a global point of access to it.

As everyone said, talking is cheap, show me code:D That’s why, let’s take a look at example.

Example

class Logger {private var logs: [String] = []static var shared :  Logger = {let instance = Logger()return instance}()

--

--