加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

德尔福Singleton模式

发布时间:2020-12-15 10:15:58 所属栏目:大数据 来源:网络整理
导读:我知道这是社区多次讨论的,但是我在Delphi中找不到一个简单的单例模式的实现。 我在C#中有一个例子: public sealed class Singleton { // Private Constructor Singleton( ) { } // Private object instantiated with private constructor static readonly
我知道这是社区多次讨论的,但是我在Delphi中找不到一个简单的单例模式的实现。
我在C#中有一个例子:
public sealed class Singleton {
  // Private Constructor
  Singleton( ) { }

  // Private object instantiated with private constructor
  static readonly Singleton instance = new Singleton( );

  // Public static property to get the object
  public static Singleton UniqueInstance {
    get { return instance;}
}

我知道在Delphi中没有这样优雅的解决方案,我看到很多关于无法正确隐藏Delphi中的构造函数(使其为私有)的讨论,所以我们需要覆盖NewInstance和FreeInstrance方法。我相信这是我在http://ibeblog.com/?p=65发现的一些实现:

type
TTestClass = class
private
  class var FInstance: TTestClass;
public                              
  class function GetInstance: TTestClass;
  class destructor DestroyClass;
end;

{ TTestClass }
class destructor TTestClass.DestroyClass;
begin
  if Assigned(FInstance) then
  FInstance.Free;
end;

class function TTestClass.GetInstance: TTestClass;
begin
  if not Assigned(FInstance) then
  FInstance := TTestClass.Create;
  Result := FInstance;
end;

你对Singleton模式的建议是什么?可以简单优雅,线程安全吗?

谢谢。

解决方法

我想如果我想要一个没有任何方法构建的类似对象的东西,我可能会使用与单元实现部分中包含的实现对象的接口。

我将通过一个全局函数(在接口部分声明)来公开接口。该实例将在完成部分中进行整理。

要获得线程安全性,我将使用关键部分(或等效的)或可能仔细实施的双重检查锁定,但认识到天真的实现只能由于x86内存模型的强大性质而起作用。

它看起来像这样:

unit uSingleton;

interface

uses
  SyncObjs;

type
  ISingleton = interface
    procedure DoStuff;
  end;

function Singleton: ISingleton;

implementation

type
  TSingleton = class(TInterfacedObject,ISingleton)
  private
    procedure DoStuff;
  end;

{ TSingleton }

procedure TSingleton.DoStuff;
begin
end;

var
  Lock: TCriticalSection;
  _Singleton: ISingleton;

function Singleton: ISingleton;
begin
  Lock.Acquire;
  Try
    if not Assigned(_Singleton) then
      _Singleton := TSingleton.Create;
    Result := _Singleton;
  Finally
    Lock.Release;
  End;
end;

initialization
  Lock := TCriticalSection.Create;

finalization
  Lock.Free;

end.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读