类的惰性属性

{在我们定义的对象(联系人)中包含的字段是对象(电话列表)时。往往这个字段不经常使用到。这样的字段称为惰性字段也就是惰性属性。
本例中的FPhoneNumbers就是这样情况。
}
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 
= class(TForm)
    Button1: TButton;
    ComboBox1: TComboBox;
    
procedure Button1Click(Sender: TObject);
  
private
    
{ Private declarations }
  
public
    
{ Public declarations }
  
end;

  TContact 
= class
  
private
    FName: 
string;
    FPhoneNumbers: TStrings;
    
function CreateFPhoneNumbers: TStrings;
    
function GetPhoneNumbers: TStrings;
    
procedure SetPhoneNumbers(const Value: TStrings);
  
public
    
constructor Create; virtual;
    
destructor Destroy; override;
    
property Name: string read FName write FName;
    
property PhoneNumbers: TStrings read GetPhoneNumbers write SetPhoneNumbers;
  
end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  
with TContact.Create do
  
begin
    Name :
= Button1.Caption;
    PhoneNumbers :
= ComboBox1.Items;
    ShowMessage(PhoneNumbers.Text);
  
end;

end;

{ TContact }

constructor TContact.Create;
begin
  
inherited;
  FPhoneNumbers :
= nil;
end;

function TContact.CreateFPhoneNumbers: TStrings;
begin
  
if (not Assigned(FPhoneNumbers)) then
    FPhoneNumbers :
= TStringList.Create;
  Result :
= FPhoneNumbers;

end;

destructor TContact.Destroy;
begin
  FPhoneNumbers.Free;
  
inherited;
end;

function TContact.GetPhoneNumbers: TStrings;
begin
  Result :
= CreateFPhoneNumbers;
end;

procedure TContact.SetPhoneNumbers(const Value: TStrings);
begin
  
if (Value = FPhoneNumbers) then Exit;
  PhoneNumbers.Assign(Value);
end;

end.
原文地址:https://www.cnblogs.com/k1727/p/1966230.html