Global instance(s) of class

Monkey Forums/Monkey Programming/Global instance(s) of class

Raz(Posted 2011) [#1]


I want to make a globally accessible instance of a class. Is the above example the best way of doing it (an instance stored globally within the relevant class)? Is there any reason why I shouldn't be doing this?

For multiple instances I, I have an array of instances stored globally within the class. Again is there any reason why I shouldn't be doing this?

Ta!


JaviCervera(Posted 2011) [#2]
This is a very typical design pattern, called "Singleton", but it is usually implemented like this:

Class SingleItem
Private
	Global singleton:SingleItem = Null
	
	'Here you add the fields for the singleton instance...
	
	Method New()
	End
Public
	Function GetItem:SingleItem()
		If singleton = Null Then singleton = New SingleItem
		Return singleton
	End
	
	'Here you add the methods for the singleton instance...
End


In this example, we have declared the constructor as Private, so it is not possible to create instances of the class. The access to the single element is done through the GetItem() function, and then we can invoke any method of the class on the object returned by GetItem().


ziggy(Posted 2011) [#3]
Wouldn't it be much more "logical" to make an abstract class that only contains globals and functions?


JaviCervera(Posted 2011) [#4]
Yeah, using global variables and functions in a class is the simplest way to implement the same behaviour, but every design pattern book will teach you this other method for being much more "purist" in OOP terms (there's an object doing the work, while there is none with the abstract class method), and because it is extensible to a more open conception of a singleton, where it is not limited to just one instance, but to an specific number of them (for example, classes which can only have 5 instances at a time).