|
It's important for some classes to have exactly one instance. Although there can be many rooms in a building they all share the same weather.
How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but doesn't keep you from instantiating multiple objects.
A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and can provide a way to access the instance. This is the Singleton pattern.
{classVar} isNil ifTrue: [ {classVar} := {target} new. ]. ^{classVar}
{classVar} isNil ifTrue: [ {classVar} := super new ]. ^{classVar}
{classVar} := nil