六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 328|回复: 0

XE2做单实例

[复制链接]

升级  28%

26

主题

26

主题

26

主题

秀才

Rank: 2

积分
92
 楼主| 发表于 2012-12-17 21:47:22 | 显示全部楼层 |阅读模式
XE2做单实例

<div id="cnblogs_post_body"><div class="cnblogs_code"> 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.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表