As a short example, a common use case for static members is to implement the singleton programming pattern. A singleton is a class for which you can instantiate only one instance that is used everywhere. Thus, a singleton implements a class that can provide instance members to an application globally in a manner analogous to how static members provide resources globally to an application.
You can create a singleton by defining a class that instantiates itself and assigns its object reference to a static read-only property when that same property is first referenced. After that point, every reference to this static property always returns an object reference to the same class instance, allowing you to access its instance members.
Thus, the following class definition shows how you can create a singleton class, SingletonProp:
CLASS SingletonProp:
DEFINE PUBLIC STATIC PROPERTY Instance AS CLASS SingletonProp NO-UNDO
GET.
PRIVATE SET.
CONSTRUCTOR PRIVATE SingletonProp( ):
/* Make the constructor private so it cannot be called from outside of
the class */
END CONSTRUCTOR.
CONSTRUCTOR STATIC SingletonProp( ):
SingletonProp:Instance = NEW SingletonProp( ).
/* Create the one single instance when the static constructor is
called */
END CONSTRUCTOR.
/* Continue with additional code for the class */
DEFINE PUBLIC PROPERTY MaxTemperature AS DECIMAL INITIAL 0.0 NO-UNDO
GET.
SET.
END CLASS.
This example class defines a PRIVATE instance constructor, and it defines a static constructor that instantiates the class using the NEW statement, which invokes the PRIVATE constructor and assigns the object reference to the static property, Instance. Note that this PUBLIC property has a PRIVATE SET accessor to ensure that only a static method or constructor of the class or another instance of the class can set the property. This example also defines a PUBLIC instance property, MaxTemperature, that can be accessed on the instance.
The following example procedure indirectly instantiates SingletonProp by referencing its static Instance property in order to assign the resulting object reference to its own object reference variable, rSingle:
DEFINE VARIABLE rSingle AS CLASS SingletonProp NO-UNDO.
rSingle = SingletonProp:Instance.
/* Displays 0 the first time this is run only */
MESSAGE "Max temp is" rSingle:MaxTemperature VIEW-AS ALERT-BOX.
It then reads and sets the value of the instance property, MaxTemperature. Note that if you re-run this procedure in the same application session, both MESSAGE statements display "Max temp is 98.6" because rSingle:MaxTemperature is already initialized from the first execution and retains its previous value.