SAS/AF Creating a Singleton Class
The contents of this document were originally posted to comp.soft-sys.sas on 6 May 2003.
Evert Von Donkelaar wrote:
> Dear Sas users,
>
> can somebody help me out, please?
> I try to make a singleton class and found many conversations about it
> but no solutions for me.
> Maybe I overlooked something.
...
I'm not sure why, but it appears you don't have to do anything. Empirical evidence suggests that if the objects metaclass _new() does not run _super() the second time an object is being instantiated, _new_ will return the prior instance.
This scl defines a class that is to be used the as metaclass of other classes. Be sure to SAVECLASS and COMPILE it.
work.singleton.SingletonClass.scl
Class WORK.SINGLETON.SINGLETON.CLASS Extends SASHELP.FSP.CLASS / ( Description="SINGLETON.CLASS") ; Public Char description / (State="O", InitialValue="Metaclass that enforces singletoness") ; _new: Public Method optional= l: update: list / ( Label="new" , State="O" , SIGNATURE="N") ; dcl list instanceList={}, num rc=0 numberOfMe=0; _getInstances(instanceList,'Y'); numberOfMe=listlen(instanceList); if (numberOfMe > 0) then do; put "there is already an instance of this class"; * if super runs here * . you will get a new instance; * if super does not run here * . the prior (first and thus only) instance will be returned * . resulting in a singleton!; * _super(l); end; else do; put "there is no object of this class"; * super has to run at least once somewhere to create an instance; _super(l); end; endmethod; endclass;
This scl defines a test class using the Singleton class as it's metaclass. Be sure to SAVECLASS it.
work.singleton.UniqueInstanceClass.scl
Class work.singleton.UniqueInstance.class Extends SASHELP.FSP.OBJECT / ( MetaClass="work.singleton.singleton.Class") ; EndClass ;
Now test the singleton to ensure _NEW_ always returns the same object identifier. COMPILE and TESTAF.
work.test.singleton.scl
init: declare work.singleton.uniqueInstance.class One = _new_ work.singleton.uniqueInstance.class (); declare work.singleton.uniqueInstance.class Two = _new_ work.singleton.uniqueInstance.class (); put One= Two=; if One = Two then put "Looks like a singleton."; call execcmd ('CANCEL'); return;
Check your LOG window, you will see something like this
numberOfMe=0 there is no object of this class numberOfMe=1 there is already an instance of this class One=4449 Two=4449 Looks like a singleton.
Voila! Singleton.
Copyright 2003 Richard A. DeVenezia This page was last updated 9 May 2003.