Reference Count

起源

Reference Count模式是一种相对简单,但实用性很强,比如COM中的引用记数就是COM生命周期控制的基础,同样也是Observer模式(详细请见Observer模式)的生命周期的基础。

目的<o:p></o:p>

利用Reference Count的模式来控制对象的生命周期。对于引用记数中对象将是可利用的对象,否则对象将析构自身。<o:p></o:p>

动机

Reference Count模式的基础与Lock的基础很相类似。唯一不同的是Lock预先定义、固定的。它的具体的类的应用时也与Lock模式类似。Reference Count模式默认一种行为方法:SetReferenced,同样当具体使用些模式时,你可以创建自己习惯的方法。如

 <o:p></o:p>

Reference Count模式在singleton模式中会有比较好的应用。<o:p></o:p>

应用

unit ReferenceCount;<o:p></o:p>

 <o:p></o:p>

 <o:p></o:p>

 <o:p></o:p>

  TRefCountSample = class (TObject)<o:p></o:p>

  private<o:p></o:p>

    FReferenceCnt: Integer;<o:p></o:p>

  protected<o:p></o:p>

    function Referenced: Boolean;<o:p></o:p>

    procedure SetReferenced(IsReferenced: Boolean);<o:p></o:p>

  public<o:p></o:p>

    procedure AddReference;<o:p></o:p>

    procedure RemoveReference;<o:p></o:p>

  end;<o:p></o:p>

 <o:p></o:p>

{<o:p></o:p>

*******************************TRefCountSample*******************************<o:p></o:p>

}<o:p></o:p>

procedure TRefCountSample.AddReference;<o:p></o:p>

begin<o:p></o:p>

  Inc(FReferenceCnt);<o:p></o:p>

  if FReferenceCnt = 1 then SetReferenced(True);<o:p></o:p>

end;<o:p></o:p>

 <o:p></o:p>

function TRefCountSample.Referenced: Boolean;<o:p></o:p>

begin<o:p></o:p>

  Result := (FReferenceCnt <> 0);<o:p></o:p>

end;<o:p></o:p>

 <o:p></o:p>

procedure TRefCountSample.RemoveReference;<o:p></o:p>

begin<o:p></o:p>

  Dec(FReferenceCnt);<o:p></o:p>

  if FReferenceCnt = 0 then SetReferenced(False);<o:p></o:p>

end;<o:p></o:p>

 <o:p></o:p>

procedure TRefCountSample.SetReferenced(IsReferenced: Boolean);<o:p></o:p>

begin<o:p></o:p>

  if not Referenced then Free;<o:p></o:p>

end;<o:p></o:p>

Delphi实例:IUnknown

IUnknown = interface<o:p></o:p>

    ['{00000000-0000-0000-C000-000000000046}']<o:p></o:p>

    …<o:p></o:p>

function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;<o:p></o:p>

    function _AddRef: Integer; stdcall;<o:p></o:p>

    function _Release: Integer; stdcall;<o:p></o:p>

  end;<o:p></o:p>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值