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