示例:影片出租店程序(添加功能)
说明:
通过对计算逻辑的提炼,可以完成一个HtmlStatement(),并复用原本Statement()内的所有计算。
代码:
type
//--顾客
TCustomer = class
private
FName: string;
FRentals: TObjectList;
function GetName: string;
function GetTotalCharge: double;
function GetTotalFrequentRenterPoints: integer;
public
constructor Create(const AName: string);
destructor Destroy; override;
//---
procedure AddRental(arg: TRental);
function Statement: string; //--统计报表
function HtmlStatement: string;
//---
property Name: string read GetName;
end;
constructor TCustomer.Create(const AName: string);
begin
FName := AName;
FRentals := TObjectList.Create;
end;
destructor TCustomer.Destroy;
begin
FRentals.Free;
//---
inherited;
end;
procedure TCustomer.AddRental(arg: TRental);
begin
FRentals.Add(arg);
end;
function TCustomer.GetName: string;
begin
Result := FName;
end;
function TCustomer.GetTotalCharge: double;
{总消费金额}
var
Rentals: TEnumeration;
each: TRental;
begin
Result := 0;
//---
Rentals := TEnumeration.Create(FRentals);
while Rentals.HasMoreElements do
begin
each := TRental(Rentals.NextElement);
Result := Result + each.GetCharge;
end;
Rentals.Free;
end;
function TCustomer.GetTotalFrequentRenterPoints: integer;
{总常客积点}
var
Rentals: TEnumeration;
each: TRental;
begin
Result := 0;
//---
Rentals := TEnumeration.Create(FRentals);
while Rentals.HasMoreElements do
begin
each := TRental(Rentals.NextElement);
Result := Result + each.GetFrequentRenterPoints;
end;
Rentals.Free;
end;
function TCustomer.Statement: string;
var
Rentals: TEnumeration;
each: TRental;
begin
Result := 'Rental Record for ' + self.Name + CRLF;
//---
Rentals := TEnumeration.Create(FRentals);
while Rentals.HasMoreElements do
begin
each := TRental(Rentals.NextElement);
//---显示此笔租借数据
Result := Result + each.Movie.Title + ' ' + FloatToStr(each.GetCharge) + CRLF;
end;
Rentals.Free;
//---结尾打印
Result := Result + 'Amount owed is ' + FloatToStr(self.GetTotalCharge) + CRLF;
Result := Result + 'You earned ' + IntToStr(self.GetTotalFrequentRenterPoints) + ' frequent renter
points';
end;
function TCustomer.HtmlStatement: string;
var
Rentals: TEnumeration;
each: TRental;
begin
Result := '<H1>Rental for <EM>' + self.Name + '</EM></H1><P>' + CRLF;
//---
Rentals := TEnumeration.Create(FRentals);
while Rentals.HasMoreElements do
begin
each := TRental(Rentals.NextElement);
//---显示此笔租借数据
Result := Result + each.Movie.Title + ':' + FloatToStr(each.GetCharge) + '<BR>' + CRLF;
end;
Rentals.Free;
//---结尾打印
Result := Result + '<P>You owe <EM>' + FloatToStr(self.GetTotalCharge) + '</EM><P>' + CRLF;
Result := Result + 'On this Rental you earned <EM>' + IntToStr(self.GetTotalFrequentRenterPoints) +
'</EM> frequent renter points<P>';
end;