Delphi 단일 모드
                                            
 1946 단어  Delphi
                    
unit Singleton;
(*
            ,             
*)
interface
uses SysUtils;
type
  TSingleton = class
  public
    class function NewInstance : TObject; override;
    class function GetInstance : TSingleton;
    destructor Destroy; override;
    procedure FreeInstance; override;
    function Address : integer;
  end;
implementation
var
  FSingleton : TSingleton = nil;
  FCanFree : Boolean;
{ TSingleton }
function TSingleton.Address: integer;
begin
  Result := Integer(Self);
end;
destructor TSingleton.Destroy;
begin
  inherited;
end;
procedure TSingleton.FreeInstance;
begin
  if not FCanFree then Exit;
  inherited FreeInstance;
  FSingleton := nil;
end;
class function TSingleton.GetInstance: TSingleton;
begin
  if not Assigned(FSingleton) then
  begin
    FSingleton := TSingleton.Create;
  end;
  Result := FSingleton;
end;
class function TSingleton.NewInstance: TObject;
begin
  if not Assigned(FSingleton) then
  begin
    FSingleton := TSingleton(inherited NewInstance);
  end;
  Result := FSingleton;
end;
initialization
  FSingleton := TSingleton.Create;
finalization
  FCanFree := True;
  if Assigned(FSingleton) then
  begin
    FSingleton.Free;
    FSingleton := nil;
  end;
end.  unit Unit15;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Singleton, StdCtrls;
type
  TForm15 = class(TForm)
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
var
  Form15: TForm15;
implementation
{$R *.dfm}
procedure TForm15.btn1Click(Sender: TObject);
var
  vTest, vTest2 : TSingleton;
begin
  vTest := TSingleton.Create;
  ShowMessage(IntToStr(vTest.Address));
  vTest2 := TSingleton.Create;
  ShowMessage(IntToStr(vTest2.Address));
//  vTest.free;
  FreeAndNil(vTest);
  vTest2.free;
end;
end.
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[Delphi] TStringBuilder그리고 꼭 사용해야만 할까? 그림처럼 Heap 영역에 "Hello" 공간을 생성하고 포인팅을 한다. "Hello World" 공간을 새로 생성한 후 포인팅을 하게 된다. 결국 "Hello" 라는 String 객체가 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.