Skip to content

Instantly share code, notes, and snippets.

@myssun0325
Last active March 27, 2018 05:26
Show Gist options
  • Save myssun0325/95d91f298900b56bda712ff9d70406f9 to your computer and use it in GitHub Desktop.
Save myssun0325/95d91f298900b56bda712ff9d70406f9 to your computer and use it in GitHub Desktop.
DIP_example
import Foundation
// 1. 적용 X
/*
class Handler {
let fm = FilesystemManager()
func handle(string: String) {
fm.save(string: string)
}
}
class FilesystemManager {
func save(string: String) {
// Open a file
// Save the string in this file
// Close the file
}
}
*/
// 2. DIP적용
class Handler {
let storage: Storage
init(storage: Storage) {
self.storage = storage
}
func handle(string: String) {
storage.save(string: string)
}
}
protocol Storage {
func save(string: String)
}
class FilesystemManager: Storage {
func save(string: String) {
// Open a file in read-mode
// Save the string in this file
// Close the file
}
}
class DatabaseManager: Storage {
func save(string: String) {
// Connect to the database
// Execute the query to save the string in a table
// Close the connection
}
}
//테스팅
/*
class StubStorage: Storage {
var isSavedCalled = false
func save(string: String) {
isSavedCalled = true
}
}
class HandlerTests {
func test_Handle_IsSaveCalled() {
let handler = Handler()
let stubStorage = StubStorage()
handler.handle(string: "test", storage: stubStorage)
XCTAssertTrue(stubStorage.isSavedCalled)
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment