I am learning Pharo and I want to understand if classes/objects like nil which belongs to UndifnedObject class have only 1 instance and act like a singleton, or is a new instance made every time we have a nil.
Let’s check what happens when we subclass a singleton class. Here, you can see that SingletonChild has the same instance of SingletonClass and also shares the same state. But there are scenarios, where we need a different instance, but should share the same state. This state sharing can be achieved using Borg singleton.
Classic Singleton creates an instance only if there is no instance created so far; otherwise, it will return the instance that is already created. Let’s take a look at the below code. Here, in the __new__ method, we will check whether an instance is created or not. If created, it will return the instance; otherwise, it will create a new instance.
Let’s list a few of the use cases of a singleton class. They are as follows: Let’s create a webcrawler that uses the benefit of a classic singleton. In this practical example, the crawler scans a webpage, fetch the links associated with the same website, and download all the images in it.
Singletons may be lazily initialized (to be discussed further) Primarily due to the fact that a singleton holds an instantiated object, whereas static classes do not, singletons have the following advantages over static classes: Singletons can have their instances swapped out (such as for testing purposes)
The symbol nil
refers to the single instance of UndefinedObject
. You will find the same for true
and false
(sole instances of True
and False
respectively).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With