好像听别人叫你穆老大哦。你的探索精神没先赞一个,我已经落伍了。是不是可以这样:TSingletonTest = classprivate constructor CreateNew;public constructor Create;
class function GetInstance(): TSingletonTest;
procedure Show();
end;
constructor TSingletonTest.Create;
begin
raise Exception.Create('do not use create of '+ClassName);
end;
constructor TSingletonTest.CreateNew;
begin
;
end;
class function TSingletonTest.GetInstance: TSingletonTest;{$J+}const inst: TSingletonTest = nil;{$J-}begin
if not Assigned(inst) then
begin
inst := TSingletonTest.CreateNew;
end;
Result := inst;
end;
procedure TSingletonTest.Show;
begin
ShowMessage('address:'+IntToStr(Integer(self)));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TSingletonTest.GetInstance.Show;
end;
C++的做法类似,不过这里没有考虑线程安全的问题。
Avalon,Delphi7不像2006,实现起来不是那么完美,如果你像释放,你看看这样如何:unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type TForm1 = class(TForm) Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(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}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);
begin
TSingletonTest.GetInstance.Show;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
TSingletonTest.GetInstance(false);
end;
initialization ;
finalization TSingletonTest.GetInstance(false);
end.
我见过override TObject的NewInstance方法实现的.其实不用那么费劲,我一般都是声明一个变量,程序开始时初始化为nil,写个函数返回它,在函数里判断一下需不需要创建就行了,比如:function GetXXX:TXXX;
begin
if FXXX=nil then
FXXX:=TXXX.Create;
Result:=FXXX;
end;
这样写很简单,而且又实现了单例模式的功能.