2

我正在实现一个对象 TTextFile,它是一个框架,用于将低级 pascal 文件函数与 OO 范例一起使用。我想向开发人员添加在同一对象中需要时将其用作 TStringList 的选项,如下所示:

 TTextFile = class(TObject)
   constructor Create(FileName: String);
   procedure OpenForRead;
   procedure OpenForWrite;
   {...}
   property Content: TStringList;
 end;

但我的问题是我希望该Content属性LoadFromFile仅在应用程序第一次使用它时才使用用户。不在Create构造中,因为文件可能太大,程序员在这种情况下更愿意使用其他函数。当Content他知道他正在使用的文件不会很大时,将使用该文件。

大文件的一个示例是包含所有客户名称和公民 ID 的列表。一个非常小的文件的示例是相同的列表,但仅包含当天等待参加的客户。

是否可以在 OO pascal 中完成?如果不可能,我将不得不制作一种激活程序或重载Create,并让程序员Content在使用前总是检查是否已加载。

4

2 回答 2

7

使用延迟初始化的概念。第一次Content读取属性时,加载文件内容,但随后保持内容可用,以便属性的后续访问不会重新读取文件。

private
  FContent: TStrings;
  function GetContent: TStrings;
public
  property Content: TStrings read GetContent;

function TTextFile.GetContent: TStrings;
begin
  if not Assigned(FContent) then begin
    FContent := TStringList.Create;
    try
      FContent.LoadFromFile(FFileName);
    except
      FContent.Free;
      FContent := nil;
      raise;
    end;
  end;
  Result := FContent;
end;
于 2013-05-23T17:52:01.537 回答
2

这当然是可能的。

更改您的类声明:

TTextFile = class(TObject)
   constructor Create(FileName: String);
   procedure OpenForRead;
   procedure OpenForWrite;
   function GetContent: TStringList;
   {...}
   property Content: TStringList read GetContent;
 end;    

并实施它:

function TTextFile.GetContent: TStringList;
begin
  Result := TStringList.Create;
  Result.LoadFromFile(FFileName);  // Presumes FileName is stored in FFileName in constructor
end;
于 2013-05-23T17:43:21.927 回答