• 以下分别为 Go 实现和 Java 实现的对比
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
interface DB {
  User SelectUser(String id)
}

public class UserService {
  private final DB db;

  public UserService(DB db) {
    this.DB = db;
  }

  public UserProfile getUserProfile(String id) {
    User user = this.DB.SelectUser(id);
    ...
    return UserProfile;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type DB interface {
  SelectUser(id string) User
}

type getUserProfile func(id string) UserProfile

func newGetUserProfile(db DB) getUserProfile{
  return func (id string) UserProfile {
    user := db.SelectUser(id)
    ...
    return userProfile
  }
}
  • 从以上的代码可以看出,Go 的实现中没有刻意去创建对象,而是实现了一个工厂函数,所以整体的实现更精简一些。