Singleton模式之Delphi实现(0分)

V

VRGL

Unregistered / Unconfirmed
GUEST, unregistred user!
type
TSingleton = class(TObject)
public
A : Integer;
class function NewInstance: TObject;
override;
procedure FreeInstance;
override;
class function RefCount: Integer;
end;

implementation
var
Instance : TSingleton = nil;
Ref_Count : Integer = 0;
procedure TSingleton.FreeInstance;
begin
Dec( Ref_Count );
if ( Ref_Count = 0 ) then
begin
Instance := nil;
// Destroy private variables here
inherited FreeInstance;
end;
end;

class function TSingleton.NewInstance: TObject;
begin
if ( not Assigned( Instance ) ) then
begin
Instance := inherited NewInstance as TSingleton;
// Initialize private variables here, like this:
TSingleton(Instance).a :3D 1;
end;
Result := Instance;
Inc( Ref_Count );
end;

class function TSingleton.RefCount: Integer;
begin
Result := Ref_Count;
end;
 
to 版主:你的这个例子意思简单明了,同时里面有com的引用计数的技术,对我们新手来说比较容易上手。但小弟
我感觉是不是 TSingleton.NewInstance TSingleton.FreeInstance 要配套调用,否则极有可能少调用一次TSingleton.FreeInstance
而造成实例的未释放;
在MM中的Singleton模式中的例子,能够永远保证只有一个实例;在finalization 里的ReleaseInstance的调用保证了实例的释放。
小弟刚学设计模式,很多东西不懂,不知以上分析是否正确。
 
Delphi中是否真的需要这个东东?
type
TSingleton = class
private
...
end;

function Singleton: TSingleton;
implementation
var
Instance: TSingleton = nil;
function Singleton: TSingleton;
begin
if not Assigned(Instance) then
Instance := TSingleton.Create...;
Result := Instance
end;

finalization
if Assigned(Instance) then
Instance.Free;
 
Delphi 1~7中有两个系统对象是这样实现的:
TClipboard
TPrinter
另外两个系统对象则是先建立,后引用变量,最后自动释放:
TApplication
TScreen
很多著名的第三方控件的管理器也是这样实现的,如:
QuantumGrid
DxInspector
XlGrid
...
 
接受答案了.
 
顶部