Jim*_*Jim 20 dependency-injection
依赖注入似乎是一件好事.一般来说,应该在需要它们的方法中注入依赖项,还是应该在类的构造函数中注入依赖项?
请参阅下面的示例以演示注入相同依赖项的两种方法.
//Inject the dependency into the methods that require ImportantClass
Class Something {
public Something()
{
//empty
}
public void A()
{
//do something without x
}
public void B(ImportantClass x)
{
//do something with x
}
public void C(ImportantClass x)
{
//do something with x
}
}
//Inject the dependency into the constructor once
Class Something {
private ImportantClass _x
public Something(ImportantClass x)
{
this._x = x;
}
public void A()
{
//do something without x
}
public void B()
{
//do something with this._x
}
public void C()
{
//do something with this._x
}
}
Run Code Online (Sandbox Code Playgroud)
joh*_*tok 14
构造函数注入的主要好处是它允许您的字段标记为final.例如:
class Foo {
private final Bar _bar;
Foo(Bar bar) {
_bar=bar;
}
}
Run Code Online (Sandbox Code Playgroud)
以下页面列出了专业人士和骗子:Guice Best Practices:
方法注入
构造函数注入
归档时间: |
|
查看次数: |
6613 次 |
最近记录: |