Ex 9.1 step 2 The TSale class: using association
Now well create a simple TSale class to store the Amount; for the Name and PhoneNo it creates a link to an associated TCustomer class. Include a third unit in the project as follows:unit SaleU;We derive TSale from TObject, and so we have no inheritance relationship between TSale and TCustomer. To establish the association relationship we declare FCustomer, of type TCustomer, as a private data member of TSale.
interface
uses CustomerU;
type
TSale = class(TObject)
private
FAmount: string;
FCustomer: TCustomer;
function GetName: string;
function GetPhone: string;
public
property Name: string read GetName;
property Phone: string read GetPhone;
property Amount: string read FAmount;
constructor Create (ACustomer: TCustomer; AnAmount: string) ;
end;
implementation
{ TSale }
constructor TSale.Create(ACustomer: TCustomer; AnAmount: string) ;
begin
inherited Create;
FCustomer := ACustomer;
FAmount := AnAmount;
end;
function TSale.GetName: string;
begin
Result := FCustomer.Name;
end;
function TSale.GetPhone: string;
begin
Result := FCustomer.PhoneNo;
end;
end.
We also provide TSale with the required FAmount private data field. To instantiate a TSale object we define an appropriate constructor. This first invokes the inherited Create to get an instance of TSale along with a (nil) FCustomer reference and an empty string for FAmount.
It then initialises the data fields to the values supplied in the parameter list. This parameter list includes an existing TCustomer object that contains the required Name and PhoneNo. We are making a shallow copy of ACustomer since we are simply creating a second reference to it. If we want any of the associated classs data or methods available outside the class, we must explicitly expose them. We want TSales user to be able to read the values of the Customers Name and PhoneNo, and so we define properties with methods to map the properties to the matching properties in TCustomer.
We also provide a directly-mapped property for the Sale Amount. If the structure of TCustomer ever changes in the future, say by the addition of a CellNo data field, TSale will need corresponding changes to its access methods and properties. Once a sale is made it can be seen as being irreversible, even if the item sold is later returned for a refund or an exchange. So we use the principles of the Immutable pattern in TSale and provide read-only properties: values (for Amount and Customer) can be assigned to the data fields only in the constructor.


