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

Graeme Geldenhuys graemeg.lists at gmail.com
Fri Dec 8 09:50:35 CET 2006


Bottom line: How can we hide the constructor of a class?  As far as I
can see you cannot decrease the visibility of a method compared to
it's inherited class. Why shouldn't we be allowed to?  C++, C# does!

I found this by trying to implement a True Singleton in Free Pascal /
Delphi.  For those that don't know, a Singleton is a Design Pattern
that allows only one instance of a class.  It seems it is impossible
to do in Free Pascal / Delphi.  :-(

See attached code for a demonstration of the problem.

And here is the output.  The first two '>> PrintData' sections are
correct and use the singleton as it should be used.  The third '>>
PrintData' section is by declaring a new variable of TSingleton and
creating it.

The problem is even though the constructor is declared in the
protected section, Free Pascal just gives a compiler warning and it
stays public.  What is the reason why we may not decrease visibility
of methods or properties?  Couldn't we add this feature to Free
Pascal? Or at least in the ObjFPC mode!

Is there another way of implementing a true singleton in Free Pascal,
maybe using some other language construct.


-----------------------  START Output  ---------------
[graemeg-linux] singleton > ./singtest
>> PrintData
hello world
---------
>> PrintData
hello world
hello world 2
---------
>> PrintData

-----------------------  END Output  ---------------

-- 
Graeme Geldenhuys

There's no place like S34° 03.168'  E018° 49.342'
-------------- next part --------------
A non-text attachment was scrubbed...
Name: sing.pas
Type: text/x-pascal
Size: 574 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20061208/e3f2c8fb/attachment.pas>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: sing2.pas
Type: text/x-pascal
Size: 607 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20061208/e3f2c8fb/attachment-0001.pas>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: singtest.pas
Type: text/x-pascal
Size: 333 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20061208/e3f2c8fb/attachment-0002.pas>


More information about the fpc-pascal mailing list