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.
Features of the Singleton pattern
- Lazy construction.
- The singleton object is not created until it is needed to be used for the first time.
- The constructor is private so you can not build new instances of the object.
- The constructor is only ever called by the getInstance function if the object does not already exist.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
Lets look at what we have created.
An instance variable that is set to null, this will hold our instance of the singleton when the getInstance function is called for the first time.
An init() function which will build our singleton. It can contain private and public variables and functions.
A public getInstance() function. This will return the instance if it already exists and or if it doesn’t, it will create it, set our instance variable and then return it.
That’s all there is to it.