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 type 10 TMyTestClass = class 11 private 12 //class var n : integer; 13 class var MyTestClass : TMyTestClass; 14 public 15 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 private 26 { Private declarations } 27 public 28 { Public declarations } 29 end; 30 31 var 32 Form11: TForm11; 33 34 implementation 35 36 {$R *.dfm} 37 38 procedure TForm11.Button1Click(Sender: TObject); 39 var 40 a : TMyTestClass; 41 begin 42 {两种方式均可,但GetInstance貌似更能清晰表面这个类是单实例。} 43 {a := TMyTestClass.Create;} 44 a := TMyTestClass.GetInstance; 45 if a <> nil then 46 Application.MessageBox(PChar(a.test), '提示信息', mb_OK); 47 end; 48 49 { TMyTestClass } 50 51 class function TMyTestClass.GetInstance: TMyTestClass; 52 begin 53 Result := TMyTestClass.Create; 54 end; 55 56 class function TMyTestClass.NewInstance: TObject; 57 begin 58 // if n = 1 then 59 // begin 60 // Result := nil; 61 // raise Exception.Create('只能创建1个实例'); 62 // end 63 // else 64 // begin 65 // Result := inherited NewInstance; 66 // Inc(n); 67 // end; 68 if MyTestClass <> nil then 69 begin 70 Result := MyTestClass; 71 end 72 else 73 begin 74 Result := inherited NewInstance; 75 MyTestClass := Result as TMyTestClass; 76 end; 77 end; 78 79 function TMyTestClass.test: string; 80 begin 81 Result := Self.ClassName; 82 end; 83 84 end.
类变量+NewInstance实现单实例,真是太Easy了。