时间: 2021-07-31 作者:daque
unit usingleton;
interface
uses sysutils;
type esingletonexception = class(exception);
tsingleton = class private // 单例类真实运用的结构因变量,此处定名为createnew constructor createnew; public // 用来遏止显式挪用,由于即使将其设为独占的, // 也不妨挪用结构因变量create, // 固然本质上挪用的是其父类的结构因变量, // 如许明显不是很理念, // 以是只好证明并在实行中激励 esingletonexception constructor create; // 类本领,归来对独一的范例 class function instance: tsingleton; end;
implementation
uses syncobjs;
var singletoninstance: tsingleton = nil;
// 用来锁定 tsingleton.instance 本领,提防多线程考察 singletonlocker: tcriticalsection = nil;
{ tsingleton }
constructor tsingleton.create;begin raise esingletonexception.create('单例类,遏止显式挪用结构因变量');end;
constructor tsingleton.createnew;begin // do somethingend;
class function tsingleton.instance: tsingleton;begin singletonlocker.enter; try if not assigned(singletoninstance) then singletoninstance := tsingleton.createnew; result := singletoninstance; finally singletonlocker.leave; end;end;
initialization singletonlocker := tcriticalsection.create;finalization singletonlocker.free;end.