起源
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>