下面实现基本可以解决你的问题
---------------------------------------------
type
//目标类
TTargetObject = class
private
FId: integer;
public
constructor Create( const AId: integer );
//Id号对外公开,而且只读。
property Id: integer read FId;
end;
//工厂类
TInstanceFactory = class
private
FIdent: integer;
FObjects: TList;
public
constructor Create;
destructor Destroy
override;
//生成目标对象
function CreateObject: TTargetObject;
end;
{ TTargetObject }
constructor TTargetObject.Create(const AId: integer);
begin
FId := AId;
end;
{ TInstanceFactory }
constructor TInstanceFactory.Create;
begin
FIdent := 0;
FObjects := TList.Create;
end;
function TInstanceFactory.CreateObject: TTargetObject;
var
LObject: TTargetObject;
begin
Result := nil;
try
LObject := TTargetObject.Create( FIdent );
if Assigned( LObject ) then
begin
Result := LObject;
Inc( FIdent )
//或通过其它方法取得唯一索引,比如GUID。
end;
except
//错误处理
end;
end;
destructor TInstanceFactory.Destroy;
begin
//对FObjects的Items中的对象做清除操作,然后再释放。
FObjects.Free;
end;
function TInstanceFactory.CreateObject: TTargetObject;
var
LObject: TTargetObject;
begin
Result := nil;
try
LObject := TTargetObject.Create( FIdent );
if Assigned( LObject ) then
begin
Result := LObject;
[red] //这里应该再加一句
FObjects.Add( LObject );[/red]
Inc( FIdent )
//或通过其它方法取得唯一索引,比如GUID。
end;
except
//错误处理
end;
end;