是否有一个Android的最佳使用API​​客户端模式? [英] Is there a best use API client pattern for Android?

查看:85
本文介绍了是否有一个Android的最佳使用API​​客户端模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,因为我不知道怎么问它,这样它会导致客观的回答这个问题似乎是主观的。有没有在Android中创建一个REST API客户端最佳使用设计模式?

This question may seem subjective because I'm not sure how to ask it so that it leads to an objective answer. Is there a best use design pattern for creating an REST API client in Android?

通常我:


  • 把我所有的API方法在一个静态APIClient类

  • 写手动序列化code到每个模型我是从API(主要是因为有时添加一个序列化库好像更复杂)获得。

  • 让活动处理成功和错误响应。

不过我也看到了很多code有不同的类别为每种类型的API调用,扩展类像AbstractAction和AbstractResponse的。这似乎是一个很多人都有自己的,非常不同的,这样做,这很奇怪,因为写一个API客户端是你必须写一个应用程序时,做的第一件事的方法。那么,有没有做一个正确的方式,或者至少是一个更好的办法做到这一点?

However I've also seen a lot of code that has distinct classes for each type of API call, extending classes like AbstractAction and AbstractResponse. It seems like a lot of people have their own, very different, ways of doing it, which is strange because writing an API client is one of the first things you have to do when writing an app. So is there a right way to do it, or at least a better way to do it?

推荐答案

的模式是多种模式的组合。它受到你应该做的活动类型。

The best pattern is a combination of various patterns. it's subjected to the type of activity you are supposed to do.

有关建议设计模式,请参见:谷歌I / O 2010 - Android的REST客户端应用程序: http://youtu.be/ xHXn3Kg2IQ

For some recommended design patterns see: Google I/O 2010 - Android REST client applications: http://youtu.be/xHXn3Kg2IQ

有关访问REST API,还有已经被设计为这一特定目的(例如,改造,大力抽射,被一些人),他们抽象的网络接入以及系列化,自己做这些,似乎矫枉过正几个库除非有特殊的理由这样做。

For accessing the rest API, there's already several libraries which are designed for this specific purpose (e.g., retrofit, volley, being some of them) they abstract the network access as well as the serialization, doing these by yourself, seems overkill unless there's specific reason to do so.

例如,在改造很容易,因为这样的:

For example, in retrofit it's easy as this:

的API作为一个接口

public interface GitHubService { 
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user); 
}

与适配器使用

RestAdapter restAdapter = new RestAdapter.Builder() 
      .setEndpoint("https://api.github.com")
      .build(); 

GitHubService service = restAdapter.create(GitHubService.class);

List<Repo> repos = service.listRepos("octocat");

这确实所有的序列化,系列化要求。

This does all the serialization, and serialization required.

有正官的例子/教程凌空这里

There is official example/tutorial on volley here

这篇关于是否有一个Android的最佳使用API​​客户端模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆