[DUG] Usage - initialization and finalization
Conor Boyd
Conor.Boyd at trimble.co.nz
Tue May 23 16:18:59 NZST 2006
I haven't really been following this thread, but...
I'm curious as to why each of your consuming units needs to keep a
reference to the singleton?
IMHO, surely the whole point about a singleton is that you don't keep
references per se to it.
When you need to access the singleton, you should just call your
Singleton function declared in your MySingletonUnit unit?
Surely that would result in a whole lot less reference counting, and
worrying about who's holding on to it and when they drop their
references, etc.
Just my 0.02c.
Cheers,
C.
-----Original Message-----
From: delphi-bounces at ns3.123.co.nz [mailto:delphi-bounces at ns3.123.co.nz]
On Behalf Of Karl @ Work
[snip]
For those that are interested, my current implementation goes something
like
this:
unit MySingletonUnit;
type
IMySingleton = interface
<guid>
end;
TMySingleton = class(TWhatever, IMySingleton);
// inc the count in _AddRef, dec it in _Release, free self when 0
end;
function Singleton: TMySingleton;
implementation
{
slightly insincere apologies for the following terminology - I use M
prefix to mean "module level variable", or to put it another way, "unit
implementation section global variable"
}
var MSingleton: TMySingleton = nil;
MISingleton: IMySingleton = nil;
function MySingleton: TMySingleton;
begin
if not Assigned(MSingleton) then
begin
// create it
MISingleton := MSingleton; // Hold an additional reference for this
unit when the singleton is created (so that it hangs around)
end;
Result := MISingleton;
end;
initialization
finalization
MISingleton := nil; // Release this unit's reference end.
Then other objects go, for example:
constructor TMyObject.Create;
begin
FISingleton := MySingleton; // Hold a reference for the lifetime of
the object, driven by the scope of the interface
or if I need to reference it outside an object, I can grab a reference
in a "module level" variable the same way the unit that contains the
singleton
does:
implementation
var
MISingleton: ISingleton;
// and somewhere in the code before I use Singleton for the first time,
the following line:
MISingleton := MySingleton; // Hold a reference for the lifetime of
this unit
initialization
finalization
MISingleton := nil; // Remove the reference during the finalization of
this unit end.
More information about the Delphi
mailing list