近日得闲,研究了一下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.
本文地址:http://com.8s8s.com/it/it5246.htm