我正在使用minOccurs处理XML,并且maxOccurs经常设置为0,1或unbounded。我有一个描述此基数的模式,以及特定的数据类型。我想构建一个跟踪基数的(Delphi)类,以及一个基于minOccurs和maxOccur字段验证其尺寸的数组。我相信使用变体是一个糟糕的设计选择,因为我会在读取之前充分了解数据类型(基于XML模式规则)。

我对OOP很新,特别是Delphi OOP,那么我最好的选择是什么呢?我梦见过像:

TComplexType = class(TObject)
  FMinOccurs: integer;
  FMaxOccurs: integer;
  FValue:     Array of Variant;
public
  constructor Create(Min: integer; Max: integer);
  procedure AddValue(Value: variant);
  function Validate() : boolean;
end;

当然,FValue最终可能是一个字符串,一个整数,一个双精度等等。因此,我相信我需要专攻:

TComplexString = class(TComplexType)
  FValue:     Array of string;
end;

现在,这是正确的方法吗?我是否必须在所有不同的类(每个类对应一种数据类型)中重载AddValue(Value:SomeType)?这似乎不太流畅,因为我将在每个AddValue方法中做同样的事情:

procedure AddValue(Value: SomeType);
begin;
  // 1) Re-shape array
  // 2) Add Value as the last (newly created) element in the array
end;

我真的很讨厌为每种类型做这件事。 (不可否认,不会有那么多类型,但我仍然认为它设计有缺陷,因为重载方法中的逻辑内容几乎相同。)有什么好的提示吗?谢谢!

有帮助吗?

解决方案

您没有指定Delphi版本,但这是泛型的经典示例(可在D2009及更高版本中使用)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top