一、静态变量
方法就是我上面所设想的那样,TObject 有一个类方法:
class function NewInstance: TObject;
virtual;
我 override 了它:
TMyObj = class(TObject)
public
class function NewInstance: TObject;
override;
end;
然后在它内部定义一个静态变量,并作如下修改:
class function TMyObj.NewInstance: TObject;
const Instance: TObject = nil;
begin
if Instance = nil then
Instance := inherited NewInstance;
Result := Instance;
end;
再写一个测试程序:
var
Form1: TForm1;
Obj1, Obj2: TMyObj;
procedure TForm1.FormCreate(Sender: TObject);
begin
Obj1 := TMyObj.Create;
Obj2 := TMyObj.Create;
if Obj1=Obj2 then
Showmessage('ok');
// Ok 显示出来了
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Obj1.Free;
//Obj2.Free;
// 这句话必须注释掉,否则会引起异常,证明二者确实是一个对象
end;