Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Singleton Class
Message
From
03/11/2005 09:36:06
 
 
To
All
General information
Forum:
Visual FoxPro
Category:
Object Oriented Programming
Title:
Singleton Class
Miscellaneous
Thread ID:
01064942
Message ID:
01064942
Views:
61
Hello,

I originally posted that in an old thread, but it looks like nobody is following it any more.
Thanks to the ideas in the aforementioned thread, I wrote a Singleton class implementing the Singleton pattern (that is, a class that can have only one instance, which can be obtained without knowing if it already exists or if it has to be created).
I give all the code at the end of the post. The way to use it is to make a class subclassing the Singleton class, and call for one instance of that class exclusively by calling GetSingleton([class name]). All additional initiation code must not be placed in the Init event, but in the Initiate method. It works OK, but there are still three little issues/questions making it not as safe as I would like.

1) Can I avoid that a user can call CREATEOBJECT directly, bypassing the GetSingleton method ?

2) Can I avoid that a user redefines the Init method in the subclass ?

3) Can it be done so that it is possible to assign the result of GetSingleton to a local variable ? For the moment, if someone does so, the created instance is then not listed in the AINSTANCE array, and a next call will create a second Singleton.

Thank you for your ideas,

David
********************************
********************************
DEFINE CLASS Singleton AS Custom
********************************
********************************

*************
FUNCTION Init
*************
	LPARAMETERS oMyObject 
	oMyObject = THIS.GetExistingInstance()
	IF ISNULL(oMyObject)
		THIS.Initiate()
		oMyObject=THIS
	ELSE
		RETURN .F.
	ENDIF
ENDFUNC
* EOF(Init)

*****************
FUNCTION Initiate
*****************
ENDFUNC

**************************************
PROTECTED FUNCTION GetExistingInstance
**************************************
	LOCAL loReturn,lcClassSeft,lnClassInst
	LOCAL ARRAY laClassInst[1]
	loReturn = .NULL.
	lcClass = This.Class 
	lnClassInst = AINSTANCE(laClassInst, lcClass)
	IF lnClassInst > 0
		lcVarName=laClassInst[1]
		loReturn = &lcVarName
	ENDIF
	RETURN loReturn
ENDFUNC
* EOF(GetExistingInstance)

*********
*********
ENDDEFINE
*********
*********
* EOF(Classe Singleton)


*********************
FUNCTION GetSingleton
*********************
LPARAMETERS cClassName
	LOCAL loResult AS Singleton
	IF EMPTY(cClassName)
		cClassName="Singleton"
	ENDIF
	CREATEOBJECT(cClassName,@loResult)
	RETURN loResult
ENDFUNC
* EOF(GetSingleton)
Next
Reply
Map
View

Click here to load this message in the networking platform