9

我在设计一个类时遇到了一些麻烦。创建客户类看起来很简单:

TCustomer = Class
  private
    FIdNumber: String;
    FName: String;
    procedure SetName(const Value: String);
    procedure SetNumber(const Value: String);
  public
    Property Name : String read FName;
    Property IdNumber : String read FIdNumber;
    Constructor Create(Number, Name  : String);
end;

constructor TCustomer.Create(ANumber, AName: String);
begin
   SetName(AName);
   SetNumber(ANumber);
end;

MyCustomer := TCustomer.Create('1', 'John Doe');

但是我的客户有更多的属性:他住在哪里,出生日期等等。

TCustomer = Class
  private
    {..snip snip..}
  public
    Property Name : String read FName;
    Property IdNumber : String read FIdNumber;
    Property Street : String read FStreet;
    Property HouseNumber : Integer : read FHouseNumber;
    ..
    ..
    ..
    Constructor Create(Number, Name, Street : String; Housenumber : Integer .. .. ..);
end;

如您所见,我最终得到了一个带有很多参数的构造函数。构造具有很多属性的对象的更好方法是什么?

4

1 回答 1

15

如果某个类需要有很多字段,我会创建一个只有强制参数的构造函数,其余的我会保留在可写属性中:

type
  TCustomer = class
  private
    FName: string;
    FIdNumber: string;
    FStreet: string;
    FHouseNumber: Integer;
  public
    // constructor is empty or just with mandatory parameters
    constructor Create;
    // properties are writeable
    property Name: string read FName write FName;
    property IdNumber: string read FIdNumber write FIdNumber;
    property Street: string read FStreet write FStreet;
    property HouseNumber: Integer read FHouseNumber write FHouseNumber;
  end;

这当然取决于您是否可以将这些属性公开为可写,但在我看来,这种用法看起来比具有许多参数的构造函数更好:

var
  Customer: TCustomer;
begin
  Customer := TCustomer.Create;
  Customer.Name := 'Name';
  Customer.IdNumber := 'ID number';
  Customer.Street := 'Street';
  Customer.HouseNumber := 12345;
end;
于 2013-03-06T15:54:01.997 回答