如何创建类的新实例? [英] How can i create a new instance of a class?
问题描述
我可以做这样的事情:
case
obj1的MyObjectTypeInstance.MyTypeEnum:
结果:= TObjectType1.Create;
obj2:
结果:= TObjectType2.Create;
obj3:
结果:= TObjectType3.Create;
结尾;
不会遵循开放/封闭原则。
最初我以为我可以做类似 Result:= MyObjectTypeInstance.Create;的事情。
这是我应该怎么做的最新猜测...
var
fooA,fooB:TFoo;
开始
fooA:= TFoo2.Create; //它可以是许多类型中的任何一种
fooB:=? //如何创建与fooA具有相同类类型的fooB?
//做
fooA.Free;
fooB。免费;
结尾;
我本以为这样会更简单!
感谢您的帮助!
您可能想创建一个Abstract Factory或Factory Method类。这些是常见的设计模式,它们是经过测试的可靠开发范例。
i have a list of class instances of various kinds. i need to be able to create a new instance of a class without knowing for sure what to create. all the objects involved have the same ancestor. the actual copying of the object's member variables is easy...it's the creation of the new object where i have a problem.
admittedly i could do something like this:
case MyObjectTypeInstance.MyTypeEnum of
obj1:
Result:=TObjectType1.Create;
obj2:
Result:=TObjectType2.Create;
obj3:
Result:=TObjectType3.Create;
end;
that wouldn't follow the "open/closed principle".
initially i thought i could do something like "Result:=MyObjectTypeInstance.Create;" but that didn't work as hoped because of destructor difficulties.
here's the latest guess how i should be doing this...
var
fooA, fooB:TFoo;
begin
fooA:=TFoo2.Create; // it could be any of many types
fooB:=? // how to create fooB of same class type as fooA????
// do something
fooA.Free;
fooB.Free;
end;
i would've thought this'd be easier!
thank you for your help!
You will probably want to create an Abstract Factory or Factory Method class. These are common Design Patterns which are tested, proven development paradigms.
这篇关于如何创建类的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!