의존성 주입(DI)
의존성 주입(DI)
의존성 주입이란? 객체 내부에서 직접 다른 객체를 생성하지 않고, 외부에서 필요한 객체를 주입하는 방법. 🎯 객체를 직접 생성하지 않고, 참조를 받아서 사용
의존성 주입없이 객체 생성하는 경우(강한 결합)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Service {
func doSomething() {
print("서비스 실행")
}
}
class Client {
private let service = Service() // 직접 객체 생성 (의존성 강함)
func execute() {
service.doSomething()
}
}
let client = Client()
client.execute()
- Client 클래스에서 직접 객체를 생성하기 때문에 Service 클래스와 강하게 결합됨.
의존성 주입하여 객체를 생성하는 경우(약한 결합)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protocol ServiceProtocol {
func doSomething()
}
class NewService: ServiceProtocol {
func doSomething() {
print("do something")
}
}
class Client {
let service: ServiceProtocol
init(service: ServiceProtocol) {
self.service = service
}
func execute() {
service.doSomething()
}
}
- 특정 프로토콜을 채택한 인스턴스라면 의존성 주입이 가능하도록 약하게 결합.
✅ 결론
✔ 강한 결합을 하면 직접 수정은 가능하지만, 유지보수성과 확장성이 떨어짐
✔ 의존성 주입(DI)을 사용하면 코드 수정 없이 다른 구현으로 교체 가능
✔ 특히 테스트, 모듈화, 기능 확장 시 DI가 필수적
This post is licensed under CC BY 4.0 by the author.