The 'SOMMSingleInstance' Metaclass

Sometimes it is necessary to define a class for which only one instance can be created. This is easily accomplished with the SOMMSingleInstance metaclass. Suppose the class "Collie" is an instance of SOMMSingleInstance. The first call to CollieNew creates the one possible instance of "Collie"; hence, subsequent calls to CollieNew return the first (and only) instance.

Any class whose metaclass is SOMMSingleInstance gets this requisite behavior; nothing further needs to be done. The first instance created is always returned by the <className>New maro.

Alternatively, the method sommGetSingleInstance does the same thing as the <className>New macro. This method invoked on a class object (for example, "Collie") is useful because the call site explicitly shows that something special is occurring and that a new object is not necessarily being created. For this reason, one might prefer the second form of creating a single-instance object to the first.

Instances of SOMMSingleInstance keep a count of the number of times somNew and sommGetSingleInstance are invoked. Each invocation of somFree decrements this count. An invocation of somFree does not actually free the single instance until the count reaches zero.

SOMMSingleInstance overrides somRenew, somRenewNoInit, somRenewNoInitNoZero, and somRenewNoZero so that a proxy is created in the space indicated in the somRenew* call. This proxy redispatches all methods to the single instance, which is always allocated in heap storage. Note that all of these methods (somRenew*) increment the reference count; therefore, somFree should be called on these objects, too. In this case, somFree decrements the reference and frees the single instance (and, of course, takes no action with respect to the storage indicated in the original somRenew* call).

If a class is an instance of SOMMSingleInstance, all of its subclasse are also instances of SOMMSingleInstance. Be aware that this also means that each subclass is allowed to have only a single instance. (This may seem obvious. However, it is a common mistake to create a framework class that must have a single instance, while at the same time expecting users of the framework to subclass the single instance class. The result is that two single-instance objects are created: one for the framework class and one for the subclass. One technique that can mitigate this scenario is based on the use of somSubstituteClass. In this case, the creator of the subclass must substitute the subclass for the framework class - before the instance of the framework class is created.)


[Back: Notes and advantages of 'before/after' usage]
[Next: The 'SOMMTraced' Metaclass]