Consultor Eletrônico



Kbase P159909: How to implement a singleton class ?
Autor   Progress Software Corporation - Progress
Acesso   Público
Publicação   11/01/2011
Status: Verified

GOAL:

How to implement a singleton class ?

GOAL:

Alternative implementation of the singleton pattern

FACT(s) (Environment):

OpenEdge 10.1C
OpenEdge 10.2x
All Supported Operating Systems

FIX:

The following is an alternate approach to implementing a singleton class. Unlike the basic implementation outlined in the documentation, this approach allows for the singleton to be deleted and re-instantiated, thus allowing the singleton to be disposed when it is no longer needed.

This is done by moving the instantiation to the static Instance property which can be called repeatedly, instead of relying on the static constructor which is only ever called once per session.
Note also that in this example, the storage space for the property is separated from the property itself - this is done to prevent infinite recursive scenarios when referencing the instance inside it's constructor or destructor.

Example singleton class:
CLASS mySingleton:

DEFINE PUBLIC STATIC PROPERTY Instance AS CLASS mySingleton NO-UNDO
GET ():
/* Returns reference to the single allowed instance. Actually instantiates
the class if no instance is active */
IF Instance = ? THEN Instance = NEW mySingleton( ).
RETURN Instance.
END GET.
PRIVATE SET.

CONSTRUCTOR PRIVATE mySingleton():
/* Make the constructor private so it cannot be called from outside of
the class */
END CONSTRUCTOR.
DESTRUCTOR PUBLIC mySingleton():
/* If this was the allowed single instance, reset the instance reference
here. Failing to do so would prevent re-instantiating */
Instance = ?.
END DESTRUCTOR.
/* basic property to allow testing class */
DEFINE PUBLIC PROPERTY Testing AS CHARACTER NO-UNDO INITIAL "testing"
GET.
PRIVATE SET.
END CLASS.

Test procedure to demonstrate how class works:
DEFINE VARIABLE myRef AS CLASS mySingleton NO-UNDO.
DEFINE VARIABLE myRef2 AS CLASS mySingleton NO-UNDO.

/* Implicit instantiating through static property */
MESSAGE mySingleton:instance:testing VIEW-AS ALERT-BOX INFO BUTTONS OK.
DELETE OBJECT mySingleton:instance.

/* Proving that getting multiple references always point to same object instance.
Also proves that re-instantiation works, first object instance was deleted. */
myRef = mySingleton:instance.
myRef2 = mySingleton:instance.
MESSAGE mySingleton:instance:testing SKIP
myRef:testing SKIP
myRef = myRef2
VIEW-AS ALERT-BOX INFO BUTTONS OK.

/* Prove further that myRef and mySingleton:instance point to the same object
instance: deleting one invalidates the other as well */
DELETE OBJECT mySingleton:instance.
MESSAGE VALID-OBJECT(myRef) VIEW-AS ALERT-BOX INFO BUTTONS OK.