Re: Singleton & Self := in constructor
From: Peter Below (TeamB) (100113.1101_at_compuXXserve.com)
Date: 01/04/04
- Next message: Peter Below (TeamB): "Re: D5 TTable Values to HTML Table"
- Previous message: Mark Wilsdorf: "Re: Thread Crash -- Get Exception?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 04 Jan 2004 20:55:03 +0100
In article <3ff0abb7$1@newsgroups.borland.com>, Sal wrote:
> I want to enforce singleton behavior in my TObject derived
> class. I'd just like to know if this approach will work.
> The basic idea is that clients can call the Constructor any
> number of times, but will always get the same singleton
> instance as a result.
>
> ///////////////////
>
> Unit MySingleton
>
> interface
>
> Uses Classes;
>
> type
> TMySingleton = class
> private
> public
> Constructor Create;
> end;
>
> implementation
>
> var
>
> Instance: TMySingleton;
>
> // TMySingleton
>
> Constructor TMySingleton.Create;
> begin
> if Instance <> Nil then
> Self := Instance
> else
> begin
> Inherited Create;
> Instance := Self;
> end;
> end;
Just for the record: this does not work. When the code flow enters your
create the instance of the class has already been created, its memory
has been allocated and initialized. So you are leaking memory like mad
here <g>. There is also the side effect that the classes
AfterConstruction method will be called on every invokation of the
constructor.
You usually need to override NewInstance and FreeInstance to implement
a singleton class. But it is much simpler to just use an interface
instead of a class. Only the interface is public and the unit contains
a factory function that returns an interface reference of this type.
The Implementation contains an Instance variable like yours, but it is
of the interface type, not the object type that implements the
interface. The object descends from TInterfaceObject, of course.
The automatic reference counting gives you singleton behaviour for
free. Of course there is a way to kill the singleton by calling
_Release on the interface reference until it is dead, but that falls
under malicious coding practices, IMO <g>.
-- Peter Below (TeamB) Use the newsgroup archives : http://www.mers.com/searchsite.html http://www.tamaracka.com/search.htm http://groups.google.com http://www.prolix.be
- Next message: Peter Below (TeamB): "Re: D5 TTable Values to HTML Table"
- Previous message: Mark Wilsdorf: "Re: Thread Crash -- Get Exception?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|