大家来看看我写的关于Delphi对单例模式的实现
希望大加多多指教,第一次用delphi写单例模式的例子.
unit PropertyMgr;
interface
uses SyncObjs,SysUtils,Classes;
{
功能:管理属性文件
设计模式原型:单例模式
}
type
EPropertyMgr = class(Exception);
TPropertyMgr = class(TObject)
private
class function createInstance:TObject;
public
class function getInstance:TPropertyMgr;
constructor create;
end;
var LockCritical:TCriticalSection;
implementation
{ TPropertyMgr }
var
Instance:TPropertyMgr;
constructor TPropertyMgr.create;//确保了外界不能直接访问该对象
begin
raise EPropertyMgr.Create('该类不能从外部访问');
end;
class function TPropertyMgr.createInstance:TObject;
begin
Result:=inherited newInstance;
end;
class function TPropertyMgr.getInstance: TPropertyMgr;//外界访问类实例的唯一方法
begin
LockCritical.Acquire;
if not Assigned(Instance) then
begin
Instance:=createInstance as TPropertyMgr;
end;
Result:=Instance;
LockCritical.Release;
end;
initialization
LockCritical:=TCriticalSection.Create;
finalization
FreeAndNil(Instance);
FreeAndNil(LockCritical);
end.