Delphi for .net中Singleton模式的实现

时间:2010-03-05 18:49:54  来源:第二电脑网  作者:第二电脑网

  第二电脑网导读:dding="5" width="99%" bgcolor="#ffffc0" border="1">unit Sayes.RD.Singleton;interfacetypeTSingleton = classstrict privateclass varinstance: TSingleton;class constructor Create;publicclass varI: Integer;s: String;class function GetInstance(): TSinglet...
  正文:近日得闲,研究了一下Delphi for .net Preview3,用它实现了在传统的Delphi中实现起来比较复杂的Singleton设计模式

文件如下:

//单元文件1


unit Sayes.RD.Singleton;

interface

type
TSingleton = class
strict private
class var
instance: TSingleton;
class constructor Create;
public
class var
I: Integer;
s: String;
class function GetInstance(): TSingleton; static;
end;

implementation

class constructor TSingleton.Create();
begin
  i := 0;
  s := 'In Singleton Class constructor';
end;

class function TSingleton.GetInstance(): TSingleton;
begin
  if instance = nil then
  begin
    instance := TSingleton.Create;
  end;
  
  GetInstance := instance;
end;

end.



//单元文件2
unit Sayes.RD.Client;

interface

uses Sayes.RD.Singleton;

type
TClient = class
procedure ExportText();
constructor Create();
end;

implementation

procedure TClient.ExportText();
var
a: Sayes.RD.Singleton.TSingleton;
b: Sayes.RD.Singleton.TSingleton;
begin
  a := TSingleton.GetInstance;
  a.i := a.i + 1;
  WriteLn(a.i);
  
  a.s := 'ssssssss';
  Writeln(a.S);
  
  b := TSingleton.GetInstance;
  b.i := a.i + 1;
  WriteLn(b.i);
  Writeln(b.s);
end;

constructor TClient.Create();
begin
  inherited;
end;

end.

//项目文件


program Singleton;

uses
Sayes.RD.Client in 'Sayes.RD.Client.pas';
var
Client: TClient;
begin
  Client := TClient.Create();
  Client.ExportText;
end.

Delphi for .net中Singleton模式的实现》由第二电脑网原创提供,转载请注明:http://www.002pc.com/master/College/Language/Delphi/13076.html


关键字:

关于《Delphi for .net中Singleton模式的实现》文章的评论

站内搜索: 高级搜索

热门搜索: Windows style 系统 tr IP QQ CPU 安装 function 注册 if td