XE2做单实例
XE2做单实例1 unit Unit11; 2 3 interface 4 5 uses 6 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, 7 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; 8 9 type10 TMyTestClass = class11 private12 //class var n : integer;13 class var MyTestClass : TMyTestClass;14 public15 function test : string;16 class function NewInstance: TObject; override;17 class function GetInstance : TMyTestClass;18 end;19 20 21 22 TForm11 = class(TForm)23 Button1: TButton;24 procedure Button1Click(Sender: TObject);25 private26 { Private declarations }27 public28 { Public declarations }29 end;30 31 var32 Form11: TForm11;33 34 implementation35 36 {$R *.dfm}37 38 procedure TForm11.Button1Click(Sender: TObject);39 var40 a : TMyTestClass;41 begin42 {两种方式均可,但GetInstance貌似更能清晰表面这个类是单实例。}43 {a := TMyTestClass.Create;}44 a := TMyTestClass.GetInstance;45 if a <> nil then46 Application.MessageBox(PChar(a.test), '提示信息', mb_OK);47 end;48 49 { TMyTestClass }50 51 class function TMyTestClass.GetInstance: TMyTestClass;52 begin53 Result := TMyTestClass.Create;54 end;55 56 class function TMyTestClass.NewInstance: TObject;57 begin58 //if n = 1 then59 //begin60 // Result := nil;61 // raise Exception.Create('只能创建1个实例');62 //end63 //else64 //begin65 // Result := inherited NewInstance;66 // Inc(n);67 //end;68 if MyTestClass <> nil then69 begin70 Result := MyTestClass;71 end72 else73 begin74 Result := inherited NewInstance;75 MyTestClass := Result as TMyTestClass;76 end;77 end;78 79 function TMyTestClass.test: string;80 begin81 Result := Self.ClassName;82 end;83 84 end.
页:
[1]