[Tutor] Singletons

David Priest priest@sfu.ca
Thu, 11 Mar 1999 22:16:09 -0800

On the wxPython list, this tidbit was posted.  It has potential for really
simplifying complex GUI design (where one GUI element would influence the
appearance of another)... but I have a problem with it.

First, the pattern:

def Singleton(parent):
    if __Singleton.instance:
        return __Singleton.instance
    __Singleton.instance = __Singleton(parent)
    return __Singleton.instance

class __Singleton:
    instance = None
    def __init__(self,parent):
         { place rest of class here }

Now, the problem: GUI stuff tend to have a bunch of methods associated with
them.  How does one access them through the singleton?  If the class were
defining a window, for instance, then that class would have a "Close()" method.

Thus, the dropdown File menu entry for "Exit" might need to jump to code
that would do pre-exitting processing (saving files, etc), and then request
the application to shut down by calling the Close() method...

def Window():
	# as above
def __Window(window):
	def __init__:
		# set up window

	def Close(self):
		# shut down app
class FileMenu(menu):
	def __init__(self, etc):
		# set up the dropdown entries

         def Exit(self):
		# process the shutdown activities
		import Main

But the singleton pattern for Window() doesn't have a Close() method, of
course.  Error city.  Of course, *this* works, but is dead ugly....
         def Exit(self):
		# process the shutdown activities
		import Main
		target = Main.Window()

So... here's this potentially *fantastic* resource -- something newbies
like me probably would take a year to think of trying -- that is rather

Of course, I've been discovering more and more that 
	"If something seems to be difficult to accomplish...
		...you're doing it wrong. Find the easy way."

Thanks for any hints, peeples!