我用Delphi实现的Singleton模式

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 netatomy 的 blog

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.

本文关键:我用Delphi实现的Singleton模式
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top