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 something
end;
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.