Common use case for static members
- Last Updated: October 8, 2020
- 2 minute read
- OpenEdge
- Version 13.0
- Documentation
Common use case for static members
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:
|
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:
|
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.