示例:创建正确的Implementor对象(缺省的实现)
说明:
创建正确Implementor对象的另外一种方法是首先选择一个缺省的实现,然后根据需要改变这个实现。
例如,如果一个collection的大小超出了一定的阈值时,它将会切换它的实现,使之更适用于表目较多的collection。
代码:
unit uBridge3;
interface
uses
Dialogs;
type
TTable = class;
{抽象类}
TCollection = class
private
FImp: TTable;
FCount: integer;
procedure SetCount(const Value: integer);
public
constructor Create;
destructor Destroy; override;
//---
procedure Operation; virtual;
property Count: integer read FCount write SetCount;
end;
TCollectionA = class(TCollection)
public
procedure Operation; override;
end;
{实现类}
TTable = class
procedure OperationImp; virtual; abstract;
end;
THash = class(TTable)
procedure OperationImp; override;
end;
TLink = class(TTable)
procedure OperationImp; override;
end;
implementation
constructor TCollection.Create;
begin
FImp := TLink.Create;
end;
destructor TCollection.Destroy;
begin
FImp.Free;
//---
inherited;
end;
procedure TCollection.Operation;
begin
FImp.OperationImp;
end;
procedure TCollection.SetCount(const Value: integer);
begin
if FCount <> Value then
begin
FCount := Value;
//---
FImp.Free;
if FCount < 100 then
FImp := TLink.Create
else
FImp := THash.Create;
end;
end;
procedure THash.OperationImp;
begin
ShowMessage('Hash');
end;
procedure TLink.OperationImp;
begin
ShowMessage('Link');
end;
procedure TCollectionA.Operation;
begin
inherited;
end;
end.
procedure TForm1.Button1Click(Sender: TObject);
var
ACollection: TCollection;
begin
ACollection := TCollectionA.Create;
try
ACollection.Operation;
//---
ACollection.Count := 200;
ACollection.Operation;
finally
ACollection.Free;
end;
end;