我在设计课程时遇到了一些麻烦。 创建客户类看起来很简单:
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;
如你所见,我最终得到了一个包含大量参数的构造函数。构造具有大量属性的对象有什么更好的方法?
答案 0 :(得分: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;