type
TSingleton = class
public
class function NewInstance : TObject;override;
procedure FreeInstance;override;
end;
TForm1 = class(TForm)
Button1: TButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
singleton:TSingleton=nil;
Ref_Count:integer=0;
implementation
{$R *.dfm}
{ TSingleton }
procedure TSingleton.FreeInstance;
begin
Dec(Ref_Count);
if Ref_Count=0 then
begin
singleton := nil;
inherited FreeInstance;
end;
end;
class function TSingleton.NewInstance: TObject;
begin
if (not Assigned(singleton)) then
begin
singleton := inherited NewInstance as TSingleton;
end;
Result := Singleton;
Inc(Ref_Count);
end;
end.
本文介绍了一种使用Delphi实现单例模式的方法。通过定义TSingleton类,并重写NewInstance和FreeInstance方法来确保在整个应用程序中只存在一个实例。此外,还提供了一个TForm1表单类作为示例。
843

被折叠的 条评论
为什么被折叠?



