适配者模式

适配者模式(Adapter Pattern)

适配者模式是一个行为模式,能够让不兼容的类型一起工作,它包含以下4个部分:

  1. object using an adapter:依赖new protocol的对象
  2. new protocol:使用所需的协议
  3. legacy object:在制定协议之前就已经存在,并且不能直接修改来遵循协议
  4. adapter:遵循协议,并将调用传递到legacy object上

新iPhone上没有耳机插口,如果你想把你的耳机插进新iPhone里,就需要一个适配者来连接彼此

什么时候应该使用适配者

类,模块和方法并不可能总是能够修改的,尤其是当他们来自第三方库时,所以有时你不得不适配它们。

你可以通过扩展一个存在的类或者新建一个类来创建一个适配者。

使用举例

在这个例子中,适配一个第三方授权服务和app内部的授权服务。

1.第三方类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Third-Party Classes
public class GoogleAuthenticator {
public func login(email: String,
password: String,
completion: @escaping (GoogleUser?, Error?) -> Void) {
// Make networking calls, which return a "Token"
let token = "special-token-value"
let user = GoogleUser(email: email, password: password, token: token)
completion(user, nil)
}
}
public struct GoogleUser {
public var email: String
public var password: String
public var token: String
}

2.授权协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// AuthenticationService
public protocol AuthenticationService {
func login(email: String,
password: String,
success: @escaping (User, Token) -> Void,
failure: @escaping (Error?) -> Void)
}
public struct User {
public let email: String
public let password: String
}
public struct Token {
public let value: String
}

3.创建适配者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class GoogleAuthenticatorAdapter: AuthenticationService {
private var authenticator = GoogleAuthenticator()
public func login(email: String,
password: String,
success: @escaping (User, Token) -> Void,
failure: @escaping (Error?) -> Void) {
authenticator.login(email: email, password: password) { (googleUser, error) in
guard let googleUser = googleUser else {
failure(error)
return
}
let user = User(email: googleUser.email, password: googleUser.password)
let token = Token(value: googleUser.token)
success(user, token)
}
}
}

4.使用适配者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// MARK: - Example
var authService: AuthenticationService = GoogleAuthenticatorAdapter()
authService.login(
email: "user@example.com", password: "password",
success: { user, token in
print("Auth succeeded: \(user.email), \(token.value)")
}, failure: { error in
if let error = error {
print("Auth failed with error: \(error)")
} else {
print("Auth failed with error: no error given")
}
})

其他参考资料

  1. 视图类和模型类去耦合,使用适配者模式:https://www.jianshu.com/p/61ade7936c93
  2. 类适配器和对象适配器:https://www.jianshu.com/p/ef756fba5b74