我在设计课堂时遇到麻烦.
创建客户类看起来很简单:
创建客户类看起来很简单:
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;
解决方法
如果某个类需要有很多字段,那么我将使用一个只有强制参数的构造函数,其余的将保留在可写属性中:
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;