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

Marc Santhoff M.Santhoff at t-online.de
Fri Dec 8 17:22:47 CET 2006


Am Freitag, den 08.12.2006, 10:50 +0200 schrieb Graeme Geldenhuys:
> 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.

One working solution is to use a global var. This is bad but acceptable
for a singleton imo. If would be nice if the variable could be hidden.
Smth like this:

...
var
	_mySingleton: TSingleton;


constructor TSingleton.create;
begin
	if not(assigned(_mySingleton)) then
	begin
		inherited;
		... do initializations ...
		_mySingleton := self;
	end;
end;

initilization
	_mySingleton := NIL;
end.

HTH,
Marc





More information about the fpc-pascal mailing list