DelphiWin32 - 生成特定类的对象

标签 delphi delphi-2009

我正在使用 Delphi 2009。我有一个包含多个项目的 TListBox。我想为每个选定的项目生成一个特定类的对象。因此,如果用户选择项目编号 2 并单击创建按钮,则会创建特定类的对象。我想实现它只是检查当前所选项目的索引值,然后使用 if-then-else。或者我应该使用类引用,即每次单击项目时,我都设置类引用的类型,然后在按钮的 OnClick 事件中创建对象?我想避免所有这些控件,只根据项目字符串的值创建对象。任何想法?非常感谢!

最佳答案

有几个选项。

简单索引

简单的解决方案是:

case ListBox1.ItemIndex of
  0 : temp := TApple.Create;
  1 : temp := TPineapple.Create;
  2 : temp := TGrape.Create;
else
  raise EFruitError.Create('Unknown fruit');
end;

很清楚,但是你必须在两个地方维护列表,这可能会导致错误。

类引用

假设所有水果都来自 TFruit,带有一个虚拟构造函数。然后你可以这样做:

procedure TForm1.FormCreate(const Sender: TObject);
begin
  ListBox1.AddObject('Apple', TApple);
  ListBox1.AddObject('Pineapple', TPineapple);
  ListBox1.AddObject('Grape', TGrape);
end;

// Event handler:
procedure TForm1.CreateButtonClick(const Sender: TObject);
begin
  if ListBox1.ItemIndex>=0 then
    temp := TFruit(ListBox1.Items.Objects[ListBox1.ItemIndex]).Create;
end;

这有单点维护。这很棒。

基于名称的引用 但是如果你想根据列表中的名称创建对象,你可以创建某种工厂:

type
  TFruitClass = class of TFruit;
  TFruitFactory = class
  public
    class function CreateFruit(const AName: string): TFruit;
    class procedure RegisterFruit(const AName: string; const AFruitClass: TFruitClass);
  end;

工厂用于将类绑定(bind)到名称。每个类都使用名称进行注册。现在您只需将名称提供给工厂,工厂就会返回所需的类。

关于DelphiWin32 - 生成特定类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246471/

相关文章:

delphi - 使用 Delphi 获取真实硬盘序列号

delphi - xul.dll和图像中的异常未在delphi应用程序内的gecko浏览器中显示

delphi - 这是Delphi 2009中的错误吗?

delphi - 为什么在 DLL 库中调用 GetLastError 时返回 0?

delphi - 确定要使用的字符集

delphi - 如果鼠标不在 VirtualTreeView (TVirtualStringTree) 上,如何禁用 MouseWheel

delphi - 如何模拟记录的继承?

delphi - 包含 TObjectList<T> 的 TGenericClass<T> 无法编译

delphi - 我怎样才能看到我的delphi应用程序当前使用了多少堆栈空间?

delphi - 我的程序如何判断 Delphi 是否正在运行?