11

为什么你会使用依赖注入框架,当你可以简单地使用下面的模式?Delphi依赖注入:框架vs委托构造器

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)Simplier

这是我会怎么使用它:

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(但简单的上述方法)。

+0

也许你可以添加一个使用DI容器的源代码示例来使声明和用法上的差异更清晰? – mjn 2011-05-10 06:27:45

+0

不确定“便利”是什么意思?影响? – 2011-05-10 13:20:35

+0

@Warren,也许OP想知道选择exeplified模式还是DI容器的原因...... – 2011-05-10 18:40:09

回答

6

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

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

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