Re: Singleton



Chris Rolliston wrote:
You could even live without ever creating an instance of the class,
since the class itself can have data (using class vars).

Well, if that were possible, using a records-with-methods approach
rather than a class would be more appropriate IMO, since otherwise, you
would be 'misusing' Delphi's 'class' idiom in a manner almost as much
as writeable typed consts 'misuse' the word 'const' - for, isn't the
first thing a person learns about objects in Delphi is that they are
always created on the heap, and so, have to be explicitly instantiated
before being used?

The main keyword here is "instantiated", you don't want to instantiate one of my "class singletons".

I wouldn't implement it that way but it is possible:

interface

type
ESingletonCreate = class(Exception)
end;

Singleton = class
private
class var FSomeData: TStrings;
public
class property SomeData: TStrings read FSomeData;
constructor Create;
end;

implementation

constructor Singleton.Create;
begin
RAISE ESingletonCreate.Create('This is a singleton class and should never be instantiated');
end;

initialization

Singleton.FSomeData := TStringList.Create;
Singleton.FSomeData.Add('Hello World!');

end.

The one thing that is missing here is a "class constructor" (there is one in Delphi.NET IIRC), so the initialization section must be used.

Otherwise you can now use this class without instantiation:

ShowMessage(Singleton.SomeData.Text);

I don't know what "records with methods" have to do with this, you still have to allocate a record on the stack to use it right? Or does a record support "class methods" ... let me check:

type
Singleton = record
private
class var FSomeData: TStrings;
public
class property SomeData: TStrings read FSomeData;
end;

This also works, but you can't prevent that someone makes an "instance" of this record as you can with a class (see the constructor above).

--
Regards
Jens
.