28 June 2015 2min read

This is not a Singleton

From Wikipedia, Singleton in Software Engineering:

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

From Wikipedia, Singleton in Mathematics

In mathematics, a singleton, also known as a unit set, is a set with exactly one element

From Apple, Cocoa Core Competences

A singleton class returns the same instance no matter how many times an application requests it. A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process.

So please…

class NotASingleton {
    static let sharedInstance = NotASingleton()

    var date: NSDate = NSDate()
}

THIS IS NOT A SINGLETON!

NotASingleton.sharedInstance.date.timeIntervalSince1970
NotASingleton().date.timeIntervalSince1970

This is just one implementation in Swift that is commonly used. But there are many others and in other languages… same rules apply.

You see something in common in all the descriptions? ONE object, ONE instance. ONE. If you allow the users of your API to create more than one instance… it’s not a Singleton.

The problem is when people reads something like this:

A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.

Which is true, but you cannot forget about the other half of the explanation.

If you enjoyed this post

Continue reading