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

Marc Santhoff M.Santhoff at t-online.de
Wed Dec 13 20:31:24 CET 2006


Am Montag, den 11.12.2006, 09:38 +0200 schrieb Graeme Geldenhuys:
> On 12/8/06, Marc Santhoff <M.Santhoff at t-online.de> wrote:
> > 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.
> 
> 
> This is kinda what I have been using all along, except, I have a
> function, that creates the instance when used for the first time.  I
> call it the Lazy mans Singleton.  It works perfectly, if the developer
> knows about the global function!  Otherwise, they might still try and
> create a instance of the class, which is what I am trying to prevent.
> 

(Coming back on this topic late, sorry)

I've tried preventing a second instance like in the sources below, and
it does work.

Besides that I'd like to know if it has some effect on allocated
ressources behind the scenes in the constructor, will it allocate
ressources never freed?

<snip>
unit singleton;
interface
{$mode objfpc}
type
  tsingleton = class
  	name: String;
  	constructor create;
  end;
implementation

var
  s: TSingleton;


constructor TSingleton.create;
begin
        if not(assigned(s)) then
        begin
                inherited;
                (*... do initializations ...*)
                s := self;
                writeln('creating new singleton');
        end else begin
        	self := s; // <-- Danger, Will Robinson!
        end;
end;

initialization
        s := NIL;
end.

end.
</snip>

<snap>
program singleton_test;
{$mode objfpc}
uses singleton;
var
	s, s2: TSingleton;
BEGIN
	s := TSingleton.create;
	s.name := 'one';
	writeln('name of s: '+s.name);
	
	s2 := TSingleton.create;
	s2.name := 'two';
	
	writeln('name of s: '+s.name);
	writeln('name of s2: '+s2.name);
END.
</snap>

Output:

$ ./singleton_test
creating new singleton
name of s: one
name of s: two
name of s2: two

If there are no drawbacks, this is a somewhat clean approach for single
threaded or low threadcount applications (which is what I use, each
application in question has it's own set of singletons)...

Marc





More information about the fpc-pascal mailing list