示例:延迟初始化对象
说明:
在Creator的构造器中不要调用工厂方法—在ConcreteCreator中该工厂方法还不可用。构造器只是将产品初始化为0,而不是创建一个具体产品。访问者返回该产品。但首先它要检查确定该产品的存在,如果产品不存在,访问者就创建它。这种技术有时被称为lazy initialization。
代码:
unit FactoryMethodUnit2;
interface
uses
Dialogs;
type
TProduct = class
public
procedure Show; virtual; abstract;
end;
TContreteProduct = class(TProduct)
public
procedure Show; override;
end;
TCreator = class
private
FProduct: TProduct;
protected
function CreateProduct(): TProduct; virtual;
public
constructor Create;
destructor Destroy; override;
//---
function GetProduct: TProduct;
end;
TContreteCreator = class(TCreator)
protected
function CreateProduct(): TProduct; override;
end;
implementation
procedure TContreteProduct.Show;
begin
showmessage('这是ContreteProduct');
end;
constructor TCreator.Create;
begin
FProduct := nil;
end;
destructor TCreator.Destroy;
begin
if assigned(FProduct) then
FProduct.Free;
//---
inherited;
end;
function TCreator.CreateProduct: TProduct;
begin
Result := nil;
end;
function TCreator.GetProduct: TProduct;
begin
if FProduct = nil then
FProduct := self.CreateProduct;
//---
result := FProduct;
end;
function TContreteCreator.CreateProduct: TProduct;
begin
Result := TContreteProduct.Create;
end;
end.
procedure TForm1.Button1Click(Sender: TObject);
var
Creator: TCreator;
begin
Creator := TContreteCreator.Create;
try
Creator.GetProduct.Show;
Creator.GetProduct.Show;
finally
Creator.Free;
end;
end;
本文介绍了一种称为延迟初始化的设计模式,该模式通过在首次访问时创建对象而非构造时创建来节省资源。文中提供了一个具体的实现案例,包括Creator和ConcreteCreator类的具体定义及其实现。

416

被折叠的 条评论
为什么被折叠?



