近日得闲,研究了一下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.