“Приспособленец”. Если объект с такими признаками есть, в нашей коллекции, берем его, если нет, создаем. Работает совместно с фабрикой
program Flyweight;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
uFlyweight in 'uFlyweight.pas';
var
bookFactory: TBookFactory;
begin
bookFactory := TBookFactory.Create();
try
bookFactory.GetBookToRead('Alice in wonderland');
bookFactory.GetBookToRead('Flying on Cooko''s nest');
bookFactory.GetBookToRead('Delphi Cookbook');
bookFactory.GetBookToRead('Delphi Cookbook');
Readln;
finally
bookFactory.Free();
end;
end.
Код шаблона “Приспособленец”
unit uFlyweight;
interface
uses
System.Generics.Collections;
type
TBook = class
private
FName: string;
public
constructor Create(aName: string);
end;
TBookFactory = class
FBooksOnMyShelve: TDictionary<string, TBook>;
function BuyNewBook(aName: string): TBook;
public
constructor Create();
destructor Destroy; override;
function GetBookToRead(aName: string): TBook;
end;
implementation
{ TBookFactory }
function TBookFactory.BuyNewBook(aName: string): TBook;
begin
Result := TBook.Create(aName);
end;
constructor TBookFactory.Create;
begin
FBooksOnMyShelve := TDictionary<string, TBook>.Create();
end;
destructor TBookFactory.Destroy;
begin
FBooksOnMyShelve.Free();
inherited;
end;
function TBookFactory.GetBookToRead(aName: string): TBook;
begin
if not FBooksOnMyShelve.TryGetValue(aName, Result) then
begin
FBooksOnMyShelve.Add(aName, BuyNewBook(aName));
Writeln(aName + ' was bought');
end
else
Writeln(aName + ' found on my shelve');
end;
{ TBook }
constructor TBook.Create(aName: string);
begin
FName := aName;
end;
end.