Protocol-Based Abstractions
Depend on protocols, not concrete types.
Protocol-Based Abstractions
Injecting a protocol instead of a concrete type lets you swap implementations freely. The consumer depends only on the behavior, not the class.
Define a Protocol
Describe the capability as a protocol. Any type that conforms can be supplied as the dependency.
protocol Logging {
func log(_ message: String)
}
print("Protocol describes behavior, not a concrete class.")All lessons in this course
- Why Dependency Injection
- Constructor Injection
- Protocol-Based Abstractions
- Mocking Dependencies in Tests