gpt4 book ai didi

delphi - 您在常见的 Delphi 编程中实现了哪些设计模式?

转载 作者:行者123 更新时间:2023-12-03 14:39:15 24 4
gpt4 key购买 nike

您在常见的 Delphi 编程中实现了哪些设计模式?在 Delphi 编程中哪些模式更容易采用? (每种语言在不同的领域都很优秀,那么使用 Delphi 时哪些模式可能是非常强大的结构?)

如果您能讲述Delphi 2009/2010 设计模式的一些变化(因为这些变化支持泛型,以及 2010 年的 RTTI),我会很高兴。

互联网上有很多文章,但它们没有讨论日常可用性和模式变化。 (他们中的大多数只是讨论语言细节、架构方面的变化)。

最佳答案

只有少数 Delphi 开发人员知道每个 Delphi 开发人员都使用 Factory pattern (delphi.about.com 有一个 example in "regular" Delphi ),但随后使用虚拟 Create 构造函数实现。

所以:是时候阐明这一点了:-)

虚拟构造函数对于类就像虚拟方法对于对象实例一样。

工厂模式的整体思想是,将确定要创建什么类型(在本例中为“类”)的事物(在本例中为“对象实例”)的逻辑与实际创建分离。

使用虚拟 Create 构造函数的工作方式如下:

TComponent 有一个 virtual Create constructor所以,它可以被任何降序类覆盖:

type
TComponent = class(TPersistent, ...)
constructor Create(AOwner: TComponent); virtual;
...
end;

例如TDirectoryListBox.Create constructor覆盖它:

type
TDirectoryListBox = class(...)
constructor Create(AOwner: TComponent); override;
...
end;

您可以将类引用(类比对象实例引用)存储在“类类型”类型的变量中。对于组件类,有一个预定义类型 TComponentClass in the Classes unit :

type
TComponentClass = class of TComponent;

当你有一个TComponentClass类型的变量(或参数)时,你可以进行多态构造,这与工厂模式非常非常相似:

var
ClassToCreate: TComponentClass;

...

procedure SomeMethodInSomeUnit;
begin
ClassToCreate := TButton;
end;

...

procedure AnotherMethodInAnotherUnit;
var
CreatedComponent: TComponent;
begin
CreatedComponent := ClassToCreate.Create(Application);
...
end;

Delphi RTL 在此使用此示例:

Result := TComponentClass(FindClass(ReadStr)).Create(nil);

这里:

// create another instance of this kind of grid
SubGrid := TCustomDBGrid(TComponentClass(Self.ClassType).Create(Self));

Delphi RTL 中的第一个用途是从 DFM 文件读取表单、数据模块、框架和组件的整个创建过程如何工作。

表单(datamodule/frame/...)类实际上有一个(已发布的)表单(datamodule/frame/...)上的组件列表。该列表包括每个组件的实例名称和类引用。当读取DFM文件时,Delphi RTL然后:

  1. 查找组件实例名称,
  2. 使用该名称查找底层类引用,
  3. 然后使用类引用动态创建正确的对象

普通的 Delphi 开发人员通常不会看到这种情况发生,但如果没有它,整个 Delphi RAD 体验将不存在。

Allen Bauer (Embarcadero 首席科学家)写了一篇短文 blog article about this topic以及。还有一个SO关于 where virtual constructors are being used 的问题.

让我知道这是否足以说明虚拟 Create 构造函数主题:-)

--杰罗恩

关于delphi - 您在常见的 Delphi 编程中实现了哪些设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1584670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com