如何创建类的新实例? [英] How can i create a new instance of a class?

查看:112
本文介绍了如何创建类的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有各种类实例的列表。我需要能够在不知道要创建什么的情况下创建类的新实例。所有涉及的对象都具有相同的祖先。实际复制对象的成员变量很容易...这是我遇到问题的新对象的创建。



我可以做这样的事情:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆