我对Delphi中可用的虚拟构造函数没有任何经验。我考虑使用虚拟构建函数的类层次重置实例为初始状态是这样的:使用虚拟构造函数重置为初始状态
A = class
end;
B = class(A)
end;
C = class(B)
end;
FooA = class
a_ : A;
constructor Create(inst : A); overload;
constructor Create; overload; virtual; abstract;
destructor Destroy; override;
function Bar : A;
end;
FooB = class(FooA)
b_ : B;
constructor Create; override;
constructor Create(inst : B); overload;
end;
FooC = class(FooB)
// ...
end;
{ FooA }
constructor FooA.Create(inst: A);
begin
inherited Create;
a_ := inst;
end;
destructor FooA.Destroy;
begin
FreeAndNil(a_);
inherited;
end;
function FooA.Bar : A;
begin
Result := a_;
a_ := nil;
// here comes the magic
Self.Create;
end;
{ FooB }
constructor FooB.Create;
begin
b_ := B.Create;
inherited Create(b_);
end;
constructor FooB.Create(inst: B);
begin
inherited Create(inst);
b_ := inst;
end;
{ FooC } // ...
var
fc : FooA;
baz : A;
begin
fc := FooC.Create;
baz := fc.Bar;
WriteLn(baz.ClassName);
FreeAndNil(baz);
FreeAndNil(fc);
ReadLn;
end.
是否有在本设计中出现任何问题/陷阱?这个简单的例子就像一个魅力,但我觉得有点不自在调用构造函数(这不构造任何东西)这样。
编辑:
我决定初始化一个有意义的名字移到法保护区,是什么让我感觉更好;-)
FooA = class
strict private
a_ : A;
strict protected
procedure SetInst; overload; virtual; abstract;
procedure SetInst(i : A); overload;
public
constructor Create;
destructor Destroy; override;
function Foo : A;
end;
为什么不重新将“创建”重命名为“程序重置;虚拟”之类的东西?并称之为无处不在?这样你就可以确定它正在做你想要的东西。 – himself 2010-12-07 14:40:57