Re: Singleton
- From: Jens Mühlenhoff <j.muehlenhoff@xxxxxxxxxxxx>
- Date: Mon, 21 Jan 2008 11:17:45 +0100
Chris Rolliston wrote:
By the by, do you have any objection to the main part of my original
suggestion, which was to define an interface for the singleton and so
hide the singleton class wholesale in the implementation section of the
unit?
It really makes it (almost) impossible to create a second instance, but
comes with several drawbacks:
- If you have properties in your singleton class then you need to write
explicit accessor methods (GetPropery, SetProperty).
- You introduce reference counting just to avoid a finalization section. (I know that initialization and finalization should be avoided when possible)
- You can't pass your singleton as a TObject (Ok, you normally don't
pass pointers to your singleton around ;-) )
The interface is of course easily replaced with an abstract class:
type
TCustomSingleton = class abstract(TObject)
strict protected
function GetMyFirstProperty: Integer; virtual; abstract;
procedure SetMyFirstProperty(const Value: Integer); virtual; abstract;
public
property MyFirstProperty: Integer read GetMyFirstProperty write SetMyFirstProperty;
procedure MyFirstProcedure; virtual; abstract;
end;
The interface version looks like this:
type
ISingleton = interface
function GetMyFirstProperty: Integer;
procedure SetMyFirstProperty(const Value: Integer);
property MyFirstProperty: Integer read GetMyFirstProperty write SetMyFirstProperty;
procedure MyFirstProcedure;
end;
Here we have the version without seperation of interface and implementation types:
type
TSingleton = class sealed(TObject) // sealed prevents the constructor check to be circumvented
private
FMyFirstProperty: Integer;
class var FInstance: TSingleton;
public
property MyFirstProperty: Integer read FMyFirstProperty write FMyFirstProperty;
constructor Create; // fires an exception when FInstance <> NIL
procedure MyFirstProcedure;
end;
None of this solutions is perfect, so YMMV.
The first solution suffers from verbosity and the need to use a finalization section. It forces you to wirte accessor methods.
The second solution forces you to create accessor methods. You also have to implement reference counting.
The third solution needs a finalization sectio.
--
Regards
Jens
.
- Follow-Ups:
- Re: Singleton
- From: Chris Rolliston
- Re: Singleton
- From: Jens Mühlenhoff
- Re: Singleton
- References:
- Singleton
- From: Alan T
- Re: Singleton
- From: Chris Rolliston
- Re: Singleton
- From: Chris Morgan
- Re: Singleton
- From: Craig Stuntz [TeamB]
- Re: Singleton
- From: Chris Rolliston
- Re: Singleton
- From: Jens Mühlenhoff
- Re: Singleton
- From: Chris Rolliston
- Re: Singleton
- From: Jens Mühlenhoff
- Re: Singleton
- From: Chris Rolliston
- Singleton
- Prev by Date: Re: What's the big deal with cross-platform?
- Next by Date: Re: What's the big deal with cross-platform?
- Previous by thread: Re: Singleton
- Next by thread: Re: Singleton
- Index(es):
Relevant Pages
|