[fpc-pascal] Implementing a true Singleton - Can we decrease the visibility of a method?

Graeme Geldenhuys graemeg.lists at gmail.com
Mon Dec 11 09:29:56 CET 2006


On 12/8/06, Dean Zobec <dean.zobec at gmail.com> wrote:
> > >> Try this.
> > >> http://bdn.borland.com/article/22576
> >
> > NewInstance/FreeInstance is what I would have recommended as well.
> >
> > > Maybe we should include an implementation in FPC by default ?
> >
> > How ? The article works as-is AFAIK.
> >
> > Btw, I think singletons are nonsense too. Why is a global variable evil,
> > and a singleton class not ?
> You are right, beware of singletons. Being a simple pattern to implement it's
> often misused and sometimes creates more problems than it solves,
> it's a global variable after all, and you should put an
> extra effort to try to avoid it as you would avoid a global variable.


I use singletons in the following cases.

gINI - Able to read/write to a application .INI file for storing a
Form's state, position and size.  It also stores specific user
settings in there.  The whole application accesses the same .INI file
and each form doesn't even know the INI filename, they just use the
methods of gINI.

gLog - Also part of tiOPF.  Used for debugging purposes.  Can log to
File, GUI Window, Console or any mix of the lot. All controlled via
command line parameters.

g<ApplicationName> - A container for a application, which contains
list objects, currently selected user, etc.  eg: gM2Application will
contain the following typical properties: a LanguageList, CentreList,
CurrentUser, CurrentCentre, SystemParameters, etc.  It's a class
encapsulating a application and acts as a container for often used
objects in my application.

For unit testing, I can for example test the LanguageList without it
being inside the gM2Application object.  It can be used stand-alone.
Things I have to test as part of gM2Application is the reference
object like CurrentUser and CurrentCentre.  I created a method called
ClearDownData specifically for unit testing, which clears all data
stored in a g<ApplicationName> object, so each unit test starts with a
fresh copy, even though it is a Singleton.

-- 
Graeme Geldenhuys

There's no place like S34° 03.168'  E018° 49.342'



More information about the fpc-pascal mailing list