11

当您可以简单地使用以下模式时,为什么还要使用依赖注入框架?

unit uSomeServiceIntf;

interface

type
  ISomeService = interface
    procedure SomeMethod;
  end;

var
  CreateSomeService: function: ISomeService;

implementation

end.

unit uSomeServiceImpl;

interface

type 
  TSomeService = class(TInterfacedObject, ISomeService)
    procedure DoSomething;
  end;

function CreateSomeService: ISomeService;

implementation 

function CreateSomeService: ISomeService;
begin
  Result := TSomeService.Create;
end;

procedure TSomeService.DoSomeThing;
begin
  ...
end;

end.

unit uInitializeSystem;

interface

procedure Initialze;

implementation

uses
  uSomeServiceIntf,
  uSomeServiceImpl;

procedure Initialze;
begin
  uSomeServiceIntf.CreateSomeService := uSomeServiceImpl.CreateSomeService;
end;

end.

我试图掌握使用框架而不是这样做的好处,但到目前为止,我只看到了这种简单方法的好处:

1)参数化构造函数更容易实现。例如: var CreateSomeOtherService: function(aValue: string);

2) 更快(无需在容器中查找)

3) 更简单

这就是我将如何使用它:

unit uBusiness;
interface
[...]
implementation

uses 
  uSomeServiceIntf;
[...]
procedure TMyBusinessClass.DoSomething;
var
  someService: ISomeService;
begin
  someService := CreateSomeService;
  someService.SomeMethod;
end;

end.

您使用 DI 框架而不是这种方法的理由是什么?

使用 DI 框架会是什么样子?

据我所知,如果您使用 DI 框架,而不是针对接口注册具体类,然后系统的使用者会询问给定框架的实现。所以会有一个注册电话:

DIFramework.Register(ISomeInterface, TSomeInterface)

当您需要 ISomeInterface 实现时,您可以向 DI 框架询问它:

var
  someInterface: ISomeInterface;
begin
  someInteface := DIFrameWork.Get(ISomeInterface) as ISomeInterface;

现在很明显,如果您确实需要传递参数来创建 ISomeInterface,那么使用 DIFramework 会变得更加复杂(但使用上述方法很简单)。

4

2 回答 2

7

var CreateSomeService在您的情况下,您必须在设计时提前知道工厂函数 ptr ( ) 的名称。当然,接口和函数 ptr 在同一个 Delphi 单元文件中耦合在一起,但这只是 Delphi 的遗物,全局变量不是线程安全的,也不是受访问保护的。

如果你在运行时得到一个接口,作为某个函数或从配置文件读取的结果——你不知道要调用哪个工厂函数来获取实现者的实际实例。

DIFrameWork.Get(ISomeInterface) as ISomeInterface对您隐藏工厂功能,因此您只需要界面,而不需要界面工厂功能。如果您尝试隐藏工厂功能,那么您还必须隐藏参数。(最终会得到类似于 DI 框架的东西)。

于 2011-05-29T02:02:04.797 回答
0

当您需要其他人制作并指示 IoC 容器创建的接口时,DI 工厂会提供帮助,有时外部库会向您隐藏实现。如果您是创建接口以及使用接口的人,则应该查看基于项目范围为您创建对象的工厂模式,并考虑将其范围限定为单例或对所有一个“交易”。

您可以为单例生成一个静态类,例如“设置”,涉及涉及多个对象状态的事务的数据库会话怎么样……那就不那么有趣了。您应该为“正确的问题”考虑正确的解决方案。

于 2021-12-29T06:20:41.850 回答