打印本文 打印本文 关闭窗口 关闭窗口
Singleton模式之Delphi实现
作者:武汉SEO闵涛  文章来源:敏韬网  点击数748  更新时间:2009/4/23 18:39:23  文章录入:mintao  责任编辑:mintao
type
  TSingleton = class(TObject)
  public
    A : Integer;
    class function NewInstance: TObject; override;
    procedure FreeInstance; override;
    class function RefCount: Integer;
  end;

implementation

var
  Instance  : TSingleton  = nil;
  Ref_Count : Integer     = 0;

procedure TSingleton.FreeInstance;
begin
  Dec( Ref_Count );
  if ( Ref_Count = 0 ) then
  begin
    Instance := nil;
    // Destroy private variables here
    inherited FreeInstance;
  end;
end;

class function TSingleton.NewInstance: TObject;
begin
  if ( not Assigned( Instance ) ) then
  begin
    Instance := inherited NewInstance as TSingleton;
    // Initialize private variables here, like this:
    TSingleton(Instance).a :3D 1;
  end;
  Result := Instance;
  Inc( Ref_Count );
end;

class function TSingleton.RefCount: Integer;
begin
  Result := Ref_Count;
end;

打印本文 打印本文 关闭窗口 关闭窗口