如何运用回调和泛型来简洁代码

来源:互联网 发布:淘宝店铺支付宝限额 编辑:程序博客网 时间:2024/06/15 19:03

回调函数运用非常广泛,例如setOnClickListener就是button的一个回调。运用好回调函数可以使接口更直观。泛型则预留了可变部分,使代码更灵活简洁。
话不多说,上代码

public class VolleyTool {    private Context mContext;    private CallBackVolley cbv;    private static RequestQueue mSingleQueue;    public VolleyTool(Context context) {        this.mContext = context;        mSingleQueue = Volley.newRequestQueue(mContext.getApplicationContext(), new MultiPartStack());    }    /**     *     * @param url 请求地址     * @param map 接口传入的参数     * @param cls 实体类     * @param callBackVolley 回调函数     */    public <T>void setCallBack(final String url, final Map<String, String> map,final Class<T> cls,final CallBackVolley callBackVolley){        VolleyTool.this.cbv = callBackVolley;        StringRequest stringRequest = new StringRequest(Request.Method.POST,                url, new Response.Listener<String>() {                    @Override                    public void onResponse(String response) {                        // 使用JSONObject给response转换编码                        Log.d("lxl", response);                        if (response != null) {                             T bean = GsonTools.changeGsonToBean(response, cls);                             cbv.OnSuccessVolley(bean);                        }                    }                }, new Response.ErrorListener() {                    @Override                    public void onErrorResponse(VolleyError error) {                        error.printStackTrace();                    }                }) {            @Override            protected Map<String, String> getParams() throws AuthFailureError {                map.put("key", "z_for_example");                return map;            }        };        MyApplicationTools.mQueue.add(stringRequest);    }}
public interface CallBackVolley {    public <T>void OnSuccessVolley(T bean);    public <T>void OnFailedVolley(String message);}

模拟登陆接口:

Map<String,String> map = new HashMap<String, String>();         map.put("phonenum", "131xxxxxxxx");         map.put("captcha", "xxxx");        VolleyTool volleyTool = new VolleyTool(this);        volleyTool.setCallBack(LOGIN_URL, map, LoginMessage.class, new CallBackVolley() {            @Override            public <T> void OnSuccessVolley(T bean) {                LoginMessage loginMessage = (LoginMessage) bean;                 if (loginMessage.result == 1) {                     //登陆成功                             }else{                    //登陆失败                }            }            @Override            public <T> void OnFailedVolley(String message) {                //请求失败            }        });

bean:

public class LoginMessage {    public String message;    public int result;    public String userId;}