Last active
May 23, 2019 10:01
-
-
Save wotjd/5c4dd72b0ab2b478d4eaabe3913c7b47 to your computer and use it in GitHub Desktop.
Swift Dependency Injection Types (https://riptutorial.com/swift/example/26345/dependency-injection-types)
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 | |
protocol Engine { | |
func startEngine() | |
func stopEngine() | |
} | |
class TrainEngine : Engine { | |
func startEngine() { | |
print("Engine started") | |
} | |
func stopEngine() { | |
print("Engine stopped") | |
} | |
} | |
protocol TrainCar { | |
var numOfSeats: Int { get } | |
func attachCar(attach: Bool) | |
} | |
class RestaurantCar : TrainCar { | |
var numOfSeats: Int { | |
get { return 30 } | |
} | |
func attachCar(attach: Bool) { | |
print("Attach car") | |
} | |
} | |
class PassengerCar: TrainCar { | |
var numOfSeats: Int { | |
get { return 50 } | |
} | |
func attachCar(attach: Bool) { | |
print("Attach car") | |
} | |
} | |
// Non DI | |
class NonDITrain { | |
let engine: Engine = TrainEngine() as Engine | |
var mainCar: TrainCar = RestaurantCar() as TrainCar | |
} | |
let nonDITrain = NonDITrain() | |
// Initializer DI | |
class InitDITrain { | |
let engine: Engine? | |
var mainCar: TrainCar? | |
init(engine: Engine) { | |
self.engine = engine | |
} | |
} | |
let initDITrain = InitDITrain(engine: TrainEngine()) | |
// Properties DI | |
class PropertiesDITrain { | |
let engine: Engine? | |
var mainCar: TrainCar? | |
init(engine: Engine) { | |
self.engine = engine | |
} | |
} | |
let propertiesDITrain = PropertiesDITrain() | |
// same as non DI until above code | |
propertiesDITrain.engine = TrainEngine() | |
propertiesDITrain.mainCar = PassengerCar() | |
// Method DI | |
class MethodDITrain { | |
let engine: Engine? | |
func repackCar(trainCar: TrainCar) { | |
trainCar.attachCar(attach: true) | |
engine?.startEngine() | |
engine?.stopEngine() | |
trainCar.attachCar(attach: false) | |
} | |
} | |
let methodDITrain = MethodDiTrain() | |
methodDITrain.repackCar(trainCar: RestaurantCar()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment