Created
May 11, 2022 14:26
-
-
Save boudhayan/2d397a06ff9e342cb940f02226b1aded to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Without Dependency Injection | |
| class Company { | |
| var name: String | |
| // `ceo` is dependency here, but Company initializes the ceo object, | |
| // `Company` knows how to initilize the ceo | |
| var ceo: Employee = Employee(name: "Steve", salary: 12344) | |
| init(name: String) { | |
| self.name = name | |
| } | |
| } | |
| class Employee { | |
| var name: String | |
| var salary: Int | |
| init(name: String, salary: Int) { | |
| self.name = name | |
| self.salary = salary | |
| } | |
| } | |
| // here we do not need to pass `ceo` object as inside Company class, it is already been taken care by the Company class itself | |
| let microsoft = Company(name: "Microsoft") | |
| //****************************************************************************************************************** | |
| // Dependency Injection | |
| class Company { | |
| var name: String | |
| // `ceo` is dependency here, but does not know how to initialize ceo object, Company expecting that whoever will initilize Company knows how to initialize ceo also. | |
| var ceo: Employee | |
| init(name: String, ceo: Employee) { | |
| self.name = name | |
| self.ceo = ceo | |
| } | |
| } | |
| class Employee { | |
| var name: String | |
| var salary: Int | |
| init(name: String, salary: Int) { | |
| self.name = name | |
| self.salary = salary | |
| } | |
| } | |
| // here we have to pass the ceo object by using the initializer of Employee class. So company does not know how to initialize or it does not have any responsibility to initialize ceo, it only knows how to use ceo. this is dependency Injection | |
| let microsoft = Company(name: "Microsoft", ceo: Employee(name: "Steve", salary: 12344)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment