有没有办法重用建设者code的改造 [英] Is there a way to reuse builder code for retrofit

查看:109
本文介绍了有没有办法重用建设者code的改造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用改造,并在每一个任务,我必须做这样的事情:

I am using Retrofit and in every task I have to do something like this:

public class MyTask extends AsyncTask<String, String, String> {

    private void someMethod() {
        final RestAdapter restAdapter = new RestAdapter.Builder()
            .setServer("http://10.0.2.2:8080")
            .build();
        final MyTaskService apiManager = restAdapter.create(MyTaskService.class);
    }

    // ...

}

什么是一个很好的方法,使这项$ C $下的干?

What is a good way to make this code DRY?

推荐答案

首先,你与所有常见的行为,声明你的父类

first you declare your parent class with all common behavior

public abstract class MyAbstractTask extends AsyncTask<String, String, String> {

 protected void someMethod() { //note that i change private to protected
  final RestAdapter restAdapter = new RestAdapter.Builder().setServer("http://10.0.2.2:8080").build();
  final MyTaskService apiManager = restAdapter.create(MyTaskService.class);
 }

}

那么,你每一项工作扩展它

then, you extend it with every task

public   class MyTask extends MyAbstractTask {

 //your someMethod() is available from everywhere in your class

}

public  class MyOtherTask extends MyAbstractTask {

 //your someMethod() is available from everywhere in your class

}


但我不知道你在哪里使用restAdapter和apiManager,如果确实需要一次每个任务创建的,因为也许你可以在这些任务之外创建它。


but i dont know where you are using restAdapter and apiManager, and if the actually need to be created once per task, since probably you can create it outside of these tasks.

如果您之外创建它们,那么你就需要使用一些你的任务里面,这也是件好事,考虑到 Dependency_injection 格局。

If you create them outside, and then you need to use something inside your task, it is also good to have in mind the Dependency_injection pattern.

此外,应避免硬编码值在你的类,如 http://10.0.2.2:8080

Also, you should avoid hardcoding values in your classes, like http://10.0.2.2:8080

您应该至少使用一个最终静态最后弦乐服务器=htt​​p://10.0.2.2:8080,然后使用,或者更好,用一个setter或构造在最内部类,并设置在活动或主控制器塔值。

You should use at least a final static final String server= "http://10.0.2.2:8080" and then use that, or better, use a setter or the constructor in the most inner class, and set tha values from the activity or the main controller.

这篇关于有没有办法重用建设者code的改造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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