大家来看看我写的关于Delphi对单例模式的实现

Martin2002 2003-04-17 10:45:48
希望大加多多指教,第一次用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.
...全文
116 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

5,386

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧