Flutter 设计模式之:适配器模式(Adapter Pattern)
介绍
适配器模式(Adapter Pattern)
是一种结构型设计模式,可将一个类转换为另一个类,使得原本不兼容而不能一起工作的那些类可以一起工作。也可用于组合多个类,以获得更多功能。
简单来说,其充当两个或多个互不理解的类之间的中介。
使用场景
常见的使用场景之一是处理 API 返回的数据。
从 REST API 请求数据时,通常会带来很多参数,但应用程序中并不总是需要所有这些参数。然后我们可以创建一个适配器来 “adapt” 应用程序真正需要的数据。
代码示例
1class UserResponse {
2 final String id;
3 final String username;
4 final String address;
5 final String career;
6 final String token;
7 final String userPhotoUrl;
8 final String tokenTransfer;
9
10 const UserResponse({
11 required this.id,
12 required this.username,
13 required this.address,
14 required this.career,
15 required this.token,
16 required this.userPhotoUrl,
17 required this.tokenTransfer,
18 });
19}
1class UserViewModel {
2 final String userName;
3 final String userPhotoUrl;
4 final String address;
5 final String career;
6
7 const UserViewModel({
8 required this.userName,
9 required this.userPhotoUrl,
10 required this.address,
11 required this.career,
12 });
13}
1class UserAdapter {
2 static UserViewModel getUserViewModel(UserResponse response) {
3 return UserViewModel(
4 userName: response.username,
5 userPhotoUrl: response.userPhotoUrl,
6 address: response.address,
7 career: response.career,
8 );
9 }
10}