Consultor Eletrônico



Kbase P159931: What is a singleton?
Autor   Progress Software Corporation - Progress
Acesso   Público
Publicação   2/10/2010
Status: Unverified

GOAL:

What is a singleton?

GOAL:

What is the common use for the static members?

FACT(s) (Environment):

OpenEdge 10.1x
OpenEdge 10.2x
All Supported Operating Systems

FIX:

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 that can only be called from within the CLASS block, 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 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.
rSingle:MaxTemperature = 98.6.
/* Displays 98.6 */
MESSAGE "Max temp is" rSingle:MaxTemperature VIEW-AS ALERT-BOX.