Created
April 1, 2016 09:52
-
-
Save yashigani/20a08636c5c572c4c635db20159c3a20 to your computer and use it in GitHub Desktop.
Cake-Pattern in Swift. inspired: https://gist.github.com/hatz48/73975371f96a93f5a05a1924bb98c1dd
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
struct User { | |
let username: String | |
} | |
extension User: CustomStringConvertible { | |
var description: String { return "username: \(username)" } | |
} | |
// DAO | |
protocol UserDAOType { | |
init() | |
func find() -> User | |
} | |
final class UserDAO: UserDAOType { | |
required init() {} | |
func find() -> User { | |
return User(username: "yashigani") | |
} | |
} | |
final class MockUserDAO: UserDAOType { | |
required init() {} | |
func find() -> User { | |
return User(username: "thai curry") | |
} | |
} | |
// Component | |
protocol UserDAOComponentType { | |
associatedtype DAO: UserDAOType | |
func userDao() -> DAO | |
} | |
extension UserDAOComponentType { | |
func userDao() -> DAO { | |
return DAO() | |
} | |
} | |
// Service | |
protocol UserService: UserDAOComponentType { | |
func fetchUser() -> User | |
} | |
extension UserService { | |
func fetchUser() -> User { | |
return userDao().find() | |
} | |
} | |
// Application | |
final class Application<T: UserDAOType>: UserService { | |
typealias DAO = T | |
} | |
let user1 = Application<UserDAO>().fetchUser() | |
let user2 = Application<MockUserDAO>().fetchUser() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment