Difference between creating new object and dependency injection

后端 未结 6 2272
粉色の甜心
粉色の甜心 2020-12-08 01:24

What is the difference between creating a new object and dependency injection? Please explain in detail.

6条回答
  •  隐瞒了意图╮
    2020-12-08 01:58

    The answer to the following question may also give the answer you are looking for: Why is the new operator an anti-pattern? Well, the simple answer is that using the new operator may create a hidden, inaccessible dependency within the containing class. This makes testing the containing class more difficult because it involves testing the hidden dependency at the same time (barring MOCK frameworks of course). However, you can avoid this situation by not using the new operator and injecting the dependent object instead. This also has the following advantages:

    • For test purposes you can inject a different object.
    • The resulting containing class is more reusable because it can support different implementations of the dependent object.

提交回复
热议问题