initial
This commit is contained in:
commit
74ae93a96e
1 changed files with 94691 additions and 0 deletions
|
|
@ -0,0 +1,48 @@
|
|||
Getting started
|
||||
|
||||
|
||||
**Dependency injection**
|
||||
https://www.youtube.com/watch?v=J1f5b4vcxCQ : Dependeny injection, the best pattern
|
||||
|
||||
Dependency
|
||||
- there r functions or objects that use other objects or functions and they r called dependency. There are 2 types of coupling.
|
||||
1. Hard coupling: Here dependency cant be changed
|
||||
2. Loose coupling: To change dependency in future
|
||||
|
||||
|
||||
Dependency injection
|
||||
- Instead of instantiating new code in constructor or function in same braces/scope we pass it instead through parameter to be used.
|
||||
- Main goal of dependency injection is to achieve loose coupling.
|
||||
eg
|
||||
without DI(Dependency Injection)
|
||||
```java
|
||||
public class Laptop{
|
||||
HardDrive obj1 = new HitachiHD();
|
||||
}
|
||||
```
|
||||
with DI
|
||||
```java
|
||||
public class Laptop{
|
||||
HardDrive obj1;
|
||||
Laptop(HardDrive obj){
|
||||
this.obj1= obj;
|
||||
}
|
||||
}
|
||||
```
|
||||
- It is possible using external service. That service is responsible for creating objects.
|
||||
- Example in spring boot
|
||||
```java
|
||||
class Laptop{
|
||||
@Autowired
|
||||
HardDrive obj1;
|
||||
}
|
||||
|
||||
@Component
|
||||
class HitachiHD implements HardDrive{
|
||||
// ...
|
||||
}
|
||||
```
|
||||
With this `@Autorired` annotation it will find the component which is tagged by `@Component` to connect to it.
|
||||
- Not only this is useful to prevent tight coupling, but also for testing.
|
||||
When we wanna test laptop
|
||||
then we may not need to check harddrive bcz it is already tested so with these we can separate it too. We can create *mock object* of the class if it is loosely coupled.
|
||||
Loading…
Reference in a new issue