Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Can you have Singleton objects in VFP?
Message
From
25/10/2005 10:05:25
 
 
To
09/07/2003 11:25:17
General information
Forum:
Visual FoxPro
Category:
Object Oriented Programming
Miscellaneous
Thread ID:
00808442
Message ID:
01061850
Views:
26
That idea has been helpful to me, and I have tried to wrap it in a Singleton class that can be inherited by any class for which I want an unique instance. That subclass should be instantiated not directly, but by calling the GetSingleton function with the class name as parameter.
It is of course still not 100% safe, in that someone could still try calling CREATEOBJECT directly, and worse, in that someone could override the Init event in the subclass.
Is there some way I can declare the Init method as final, that is, not overrideable ?
Is there anything else I missed in the way I implemented that pattern ?
********************************
********************************
DEFINE CLASS Singleton AS Custom
********************************
********************************

*************
FUNCTION Init
*************
	LPARAMETERS oMyObject 
	oMyObject = THIS.GetExistingInstance()
	IF ISNULL(oMyObject)
		oMyObject=THIS
	ELSE
		RETURN .F.
	ENDIF
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

*********
*********
ENDDEFINE
*********
*********

*********************
FUNCTION GetSingleton
*********************
LPARAMETERS cClassName
	LOCAL loResult AS Singleton
	IF EMPTY(cClassName)
		cClassName="Singleton"
	ENDIF
	CREATEOBJECT(cClassName,@loResult)
	IF !InstanceOf(loResult,"Singleton")
		ERROR "The class "+cClassName+" does not inherit of the Singleton class"
	ENDIF
	RETURN loResult
ENDFUNC
Regards,
David

PS The InstanceOf function is a custom one, using ACLASS to check whether an objet is an instance of a class.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform