Created by
Stefan Glienke
| program ArchiveFactoryDemo;
{$APPTYPE CONSOLE}
uses
Spring.Container,
Spring.Container.Core,
IOUtils,
SysUtils;
type
IArchive = interface
['{EA8545A0-A466-4DCF-9FE1-0B96F853B9C4}']
end;
TFileArchive = class(TInterfacedObject, IArchive)
constructor Create(const path: string);
end;
TFolderArchive = class(TInterfacedObject, IArchive)
constructor Create(const path: string);
end;
IArchiveFactory = interface
['{02585F0C-D376-4530-BC3D-0175787A92E2}']
function CreateArchive(const path: string): IArchive;
end;
TArchiveFactory = class(TInterfacedObject, IArchiveFactory)
private
fContainer: TContainer;
public
constructor Create(const container: TContainer);
function CreateArchive(const path: string): IArchive;
end;
{ TFileArchive }
constructor TFileArchive.Create(const path: string);
begin
Writeln(path);
end;
{ TFolderArchive }
constructor TFolderArchive.Create(const path: string);
begin
Writeln(path);
end;
{ TArchiveFactory }
constructor TArchiveFactory.Create(const container: TContainer);
begin
inherited Create;
fContainer := container;
end;
function TArchiveFactory.CreateArchive(const path: string): IArchive;
begin
if TDirectory.Exists(path) then
Result := fContainer.Resolve<IArchive>('folder', [path])
else if TFile.Exists(path) then
Result := fContainer.Resolve<IArchive>('file', [path])
else
raise EPathNotFoundException.Create(path);
end;
procedure RegisterTypes(const container: TContainer);
begin
container.RegisterType<IArchive, TFileArchive>('file');
container.RegisterType<IArchive, TFolderArchive>('folder');
container.RegisterType<IArchiveFactory, TArchiveFactory>;
container.RegisterInstance(container);
container.Build;
end;
procedure Main;
var
factory: IArchiveFactory;
archive: IArchive;
begin
RegisterTypes(GlobalContainer);
factory := GlobalContainer.Resolve<IArchiveFactory>;
archive := factory.CreateArchive('C:\Program Files (x86)');
Assert(archive is TFolderArchive);
archive := factory.CreateArchive('C:\Windows\Notepad.exe');
Assert(archive is TFileArchive);
end;
begin
try
Main;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
|