to wzwcn你那方法至少用到了全局变量这在楼主眼里不是完美的单例 最多算是个山寨的单例罢了to abszo你的方法不错 但有个前提 使用者不知道CreateNew 否则你的这个单例就完美了但是 比如这样unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type TForm1 = class(TForm) Button1: TButton;
procedure Button1Click(Sender: TObject);
private { Private declarations } public { Public declarations } end;
TSingletonTest = class private constructor CreateNew;
public constructor Create;
class function GetInstance(GetFlag: Boolean = true): TSingletonTest;
procedure Show();
end;
var Form1: TForm1;implementation{$R *.dfm}{ TSingletonTest }constructor TSingletonTest.Create;
begin
raise Exception.Create('do not use create of '+ClassName);
end;
constructor TSingletonTest.CreateNew;
begin
;
end;
class function TSingletonTest.GetInstance(GetFlag: Boolean = true): TSingletonTest;{$J+}const inst: TSingletonTest = nil;{$J-}begin
if GetFlag then
begin
if not Assigned(inst) then
begin
inst := TSingletonTest.CreateNew;
end;
end else
begin
if Assigned(inst) then
begin
inst.Free;
inst := nil;
end;
end;
Result := inst;
end;
procedure TSingletonTest.Show;
begin
ShowMessage('address:'+IntToStr(Integer(self)));
end;
procedure TForm1.Button1Click(Sender: TObject);var a:TSingletonTest;
a2:TSingletonTest;
begin
a := TSingletonTest.CreateNew;
a.Show;
a2 := TSingletonTest.CreateNew;
a2.Show;
end;
end.
我依然得到了2个实例 用D7去实现绝对java式的单例 或者说完美的单例 窃以为 不可能