안녕하세요.
오늘은 Design Pattern 중에 Adapter Pattern에 대해서 공부한 것을 소개하려고 합니다!
public class NaverAuthenticator {
public func login(
email: String,
password: String,
completion: @escaping (NaverUser?, Error?) -> Void
) {
let token = "token"
let user = NaverUser(email: email,
password: password,
token: token)
completion(user, nil)
}
}
public struct NaverUser {
public var email: String
public var password: String
public var token: String
}
protocol AuthenticationService {
func login(
email: String,
password: String,
success: @escaping (User, Token) -> Void,
failure: @escaping (Error?) -> Void
)
}
struct User {
public let email: String
public let password: String
}
struct Token {
public let value: String
}
class NaverAuthenticatorAdapter : AuthenticationService {
private var authenticator = NaverAuthenticator()
func login(
email: String,
password: String,
success: @escaping (User, Token) -> Void,
failure: @escaping (Error?) -> Void
) {
authenticator.login(email: email, password: password) { (naverUser, error) in
guard let naverUser = naverUser else {
failure(error)
return
}
let user = User(email: naverUser.email, password: naverUser.password)
let token = Token(value: naverUser.token)
success(user, token)
}
}
}
class AuthManager {
var authService : AuthenticationService?
init(authService: AuthenticationService) {
self.authService = authService
}
func login() {
authService?.login(
email: "email",
password: "password",
success: { user, token in
print("Auth succeeded: \(user.email), \(token.value)")
},
failure: { error in
print("Auth failed")
})
}
}
let authManager = AuthManager(authService: NaverAuthenticatorAdapter())
authManager.login()
https://ko.wikipedia.org/wiki/%EC%96%B4%EB%8C%91%ED%84%B0_%ED%8C%A8%ED%84%B4
https://haningya.tistory.com/265
https://icksw.tistory.com/241
https://medium.com/swiftcraft/swift-solutions-adapter-pattern-a2118a6a2910