大雀软件园

首页 软件下载 安卓市场 苹果市场 电脑游戏 安卓游戏 文章资讯 驱动下载
技术开发 网页设计 图形图象 数据库 网络媒体 网络安全 站长CLUB 操作系统 媒体动画 安卓相关
当前位置: 首页 -> 技术开发 -> Script -> 用Delphi实现的Singleton模式

用Delphi实现的Singleton模式

时间: 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.

热门阅览

最新排行

Copyright © 2019-2021 大雀软件园(www.daque.cn) All Rights Reserved.