组合根

设计模式 / 整洁架构模式
image

uses System.SysUtils, System.Generics.Collections;

type
  TItem = TPair<string, Integer>;

  //entity
  TOrder = record
    Id, Total: Integer;
    function Payable: Integer;
  end;

  //gateway
  ICatalog = interface
    function TryPrice(const Sku: string;
      out Price: Integer): Boolean;
  end;

  //repository
  IOrders = interface
    procedure Save(const Order: TOrder);
    function Count: Integer;
  end;

  //output port
  IReport = interface
    procedure Say(const Text: string);
  end;

  //input port
  IPlaceOrder = interface
    procedure Place(const Items: array of TItem);
  end;

  //use case: asks for its parts, never builds them
  TPlaceOrder = class(TInterfacedObject, IPlaceOrder)
  private
    FCatalog: ICatalog;
    FOrders: IOrders;
    FReport: IReport;
  public
    constructor Create(const Catalog: ICatalog;
      const Orders: IOrders; const Report: IReport);
    procedure Place(const Items: array of TItem);
  end;

  //adapters
  TPriceList = class(TInterfacedObject, ICatalog)
    function TryPrice(const Sku: string;
      out Price: Integer): Boolean;
  end;

  TMemoryOrders = class(TInterfacedObject, IOrders)
  private
    FRows: TArray<TOrder>;
  public
    procedure Save(const Order: TOrder);
    function Count: Integer;
  end;

  TConsoleReport = class(TInterfacedObject, IReport)
    procedure Say(const Text: string);
  end;

  TSilentReport = class(TInterfacedObject, IReport)
    procedure Say(const Text: string);
  end;

  //composition root: the only place that sees every layer
  //at once, and the only place where an adapter is built;
  //a record of interfaces, so reference counting frees
  //every part it built and nobody calls Free
  TShopApp = record
    UseCase: IPlaceOrder;
    Orders: IOrders;
    class function Loud: TShopApp; static;
    class function Quiet: TShopApp; static;
  end;

function TOrder.Payable: Integer;
begin
  Result := Total;
  if Total >= 200 then
    Dec(Result, Total div 10);
end;

constructor TPlaceOrder.Create(const Catalog: ICatalog;
  const Orders: IOrders; const Report: IReport);
begin
  FCatalog := Catalog;
  FOrders := Orders;
  FReport := Report;
end;

procedure TPlaceOrder.Place(const Items: array of TItem);
var
  Order: TOrder;
  Item: TItem;
  Price: Integer;
begin
  Order := Default(TOrder);
  for Item in Items do
    if FCatalog.TryPrice(Item.Key, Price) then
      Inc(Order.Total, Price * Item.Value)
    else
    begin
      FReport.Say('no ' + Item.Key);
      Exit;
    end;
  //the repository numbers the orders by its rows
  Order.Id := 1001 + FOrders.Count;
  FOrders.Save(Order);
  FReport.Say(Format('order %d for %d',
    [Order.Id, Order.Payable]));
end;

function TPriceList.TryPrice(const Sku: string;
  out Price: Integer): Boolean;
begin
  Price := 0;
  if Sku = 'pen' then
    Price := 30
  else if Sku = 'lamp' then
    Price := 190;
  Result := Price > 0;
end;

procedure TMemoryOrders.Save(const Order: TOrder);
begin
  FRows := FRows + [Order];
end;

function TMemoryOrders.Count: Integer;
begin
  Result := Length(FRows);
end;

procedure TConsoleReport.Say(const Text: string);
begin
  WriteLn(Text);
end;

procedure TSilentReport.Say(const Text: string);
begin
end;

class function TShopApp.Loud: TShopApp;
begin
  Result.Orders := TMemoryOrders.Create;
  Result.UseCase := TPlaceOrder.Create(TPriceList.Create,
    Result.Orders, TConsoleReport.Create);
end;

class function TShopApp.Quiet: TShopApp;
begin
  Result.Orders := TMemoryOrders.Create;
  Result.UseCase := TPlaceOrder.Create(TPriceList.Create,
    Result.Orders, TSilentReport.Create);
end;

//client code
var
  App: TShopApp;
begin
  App := TShopApp.Loud;
  App.UseCase.Place([TItem.Create('pen', 2),
    TItem.Create('lamp', 1)]);
  App.UseCase.Place([TItem.Create('chair', 1)]);

  //a second root builds the same use case differently;
  //the first one and all its parts are freed right here
  App := TShopApp.Quiet;
  App.UseCase.Place([TItem.Create('lamp', 1)]);
  WriteLn('saved ', App.Orders.Count);
  //printed: order 1001 for 225
  //         no chair
  //         saved 1
end.


A composition root is the only place where the layers are connected and the adapters are built; the rest of the application only asks for its parts.
Read more

问题。用例需要一个价格目录、一个订单存储,以及一种报告结果的途径。如果用例自己创建这些部件,它就会指明外层的适配器,并依赖于它们。测试也无法为它提供别的部件。如果程序的每个部分都自行构建自己的部件,就没有人能看清应用程序是如何连接起来的。

思路。组合根是唯一一个连接各层、构建适配器的地方。适配器是实现端口的外层代码,而端口是内层声明的接口。用例只通过端口索取自己的部件,从不自己构建它们。组合根同时了解每一层,这正是它的职责。其余所有代码都遵守依赖规则:内层代码从不了解外层代码。这不需要任何框架或容器:组合根就是程序启动处的普通代码。

如何阅读示例。用例索取三个端口:一个查询价格的网关、一个保存订单的仓库,以及一个用于报告的输出端口。外层为它们提供了适配器:内存中的目录和存储,一个会打印的报告,还有一个什么也不说的报告。示例把应用程序构建了两次。第一次构建中,报告会打印:客户端代码下了订单 1001,应付 225,又下了一个含未知商品的订单。第二次构建使用静默的报告,因此它的订单什么也不打印。只有已保存订单的数量表明它们确实被保存了。两次构建中的用例完全相同。

何时使用。每个应用程序都有一个组合根,位于它的启动处;测试可以有自己的小型组合根,使用假的适配器。没有端口的短脚本不需要组合根。

常见错误。在用例内部创建适配器,哪怕只有一次。这样用例就依赖于外层,组合根也不再能展示应用程序是如何连接起来的。