January 2024
Intermediate to advanced
718 pages
20h 15m
English
The Singleton design pattern ensures that only one instance of a particular class may be created for the lifetime of a program.
The Singleton module makes this simple to implement. Mix the Singleton module into each class that’s to be a singleton, and that class’s new method will be made private. In its place, users of the class call the method instance, which returns a singleton instance of that class.
Ruby overrides a few other methods of the class when Singleton is mixed in: inherited, clone, _load, and dup, all of which are changed to prevent multiple instances of the class from existing.
In this example, the two instances of MyClass are the same object:
| | require "singleton" |
| | |
| | class MyClass |
| | attr_accessor ... |
Read now
Unlock full access