Created
August 7, 2021 08:15
-
-
Save JarvisTheAvenger/504cb82ff1bd460b6c0ae2440bf175b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Dependency Injection | |
/* | |
Dependency Injection is often used with the intention of writing code that is loosely coupled, and thus, easier to test. | |
Types of dependecy injection: | |
1. Property Injection | |
2. Constructor Injection | |
3. Interface Injection | |
*/ | |
// 1. Property Injection | |
struct Profession { | |
var name : String | |
} | |
// This involves tight coupling and creating it's own dependency | |
struct George { | |
var profession = Profession(name: "Engineer") // This is tight coupling | |
var subProfession : Profession? | |
} | |
var user = George() | |
user.subProfession = Profession(name: "Tester") // This is property injection | |
//2. Constructor Injection | |
struct Tony { | |
var profession : Profession | |
init(_ profession: Profession) { | |
self.profession = profession | |
} | |
} | |
let tony = Tony(Profession(name: "Doctor")) | |
//3. Interface Injection | |
protocol Dependency {} | |
protocol HasDependency { | |
func setDependency(_ dependency: Dependency) | |
} | |
protocol DoesSomething { | |
func doSomething() | |
} | |
class Client: HasDependency, DoesSomething { | |
private var dependency: Dependency! | |
func setDependency(_ dependency: Dependency) { | |
self.dependency = dependency | |
} | |
func doSomething() { | |
// Does something with a dependency | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment