Dependency injection is a very simple concept, but many articles have explained this concept in a very complex way. For example, many people may have read the article http://www.martinfowler.com/articles/injection.html, and this article is very successful. In fact, dependency injection is to input an instance variable to an object. Let's look at an example of dependency non-injection. There are many instance variables in the class, and we turn them into "dependencies ". Most people call them variables, or instance variables.
public class Example { private DatabaseThingie myDatabase; public Example() { myDatabase = new DatabaseThingie(); } public void DoStuff() { ... myDatabase.GetData(); ... } }
Here we have a variable, or "dependency", myDatabase. This instance is only initialized in the constructor. Injection is not reflected.
If we want to pass a variable to the constructor. That is to inject "dependency" and "injection" into the class. Then, when we use variable dependency), we use the objects we pass in, rather than the objects we create. The following is an example of dependency injection.
public class Example { private DatabaseThingie myDatabase; public Example() { myDatabase = new DatabaseThingie(); } public Example(DatabaseThingie useThisDatabaseInstead) { myDatabase = useThisDatabaseInstead; } public void DoStuff() { ... myDatabase.GetData(); ... } }
This is the concept of dependency injection. The rest is how to deal with various variables. You can set the dependency in the specified setter method. You can also set the dependency by calling the setter method in the specified interface. You can also use this dependency as an interface and then use polymorphism to pass the dependency in some cases.
The following question is why dependency injection is used. At least, it can easily isolate a class during code testing.
Public class ExampleTest {void TestDoStuff () {MockDatabase mockDatabase = new MockDatabase (); // MockDatabase is a subclass of DatabaseThingie, so we can inject Example example = new Example (mockDatabase) here ); example. doStuff (); mockDatabase. examples () ;}} public class Example {private DatabaseThingie myDatabase; public Example () {myDatabase = new DatabaseThingie ();} public Example (DatabaseThingie useThisDatabaseInstead) {myDatabase = databases ;} public void DoStuff (){... myDatabase. getData ();...}}
In this simple way, dependency injection is to pass an instance variable. Martin Fowler classifies dependency injection into three types.
1. Interface Injection
2. Set Value Injection
3. constructor Injection
For more information, see http://www.cnblogs.com/xingyukun/archive/2007/10/20/931331.html.
This article is from the "one blog" blog, please be sure to keep this source http://cnn237111.blog.51cto.com/2359144/928690