使用 Android 中的命令模式结合 Http 请求处理程序来处理其结果

Using the Command Pattern in Android in combination with an Http Request Handler to handle its result

我的实际问题在页面底部,可能不需要您查看我的所有代码。

所以我想我想在我的 Android 应用程序中使用命令模式。我有一个 class HttpRequestHandler 其中 extends AsyncTask 因此有 doInBackgroundonPostExecute 方法。 HttpRequestHandler 接受一个 URL 和一个 HttpRequest 类型作为参数。

我想要做的是将一个方法(以接口的形式)传递给 HttpRequestHandler 以便在 onPostExecute 中我可以调用该方法并让它显示得到的结果来自给定文本视图中的 Http 请求。这样我就不必在 onPostExecute

中使用巨大的 switch(case)

虽然我需要一些执行方面的帮助。在这种情况下,我有两个单独的 class 实现命令。

public interface Command{
    public void execute(JSONObject json);
}

public class DisplayResult implements Command{

    public TextView textview;

    public DisplayResult(TextView textview){
        this.textview = textview;
    }
    @Override
    public void execute(JSONObject output){
        textview.setText(output.getString("mystring")
    }
}

public class ConfirmPost implements Command{

    public ConfirmPost(){
    }
    @Override
    public void execute(JSONObject output){
        Log.d("Success! ","POST successfull");
    }
}

以及对 HTTPRequestHandler 的两次调用,一次传递 DisplayResult,一次传递 ConfirmPost class。 public 静态无效

TextView mytextview = (TextView) findViewById(R.id.mytextview);
new HttpRequestHandler(new DisplayResult(mytextview)).execute("myurl","GET");

new HttpRequestHandler(new ConfirmPost()).execute("myurl","POST");

现在我的 HttpRequestHandler 遇到了问题。

public class HttpRequestHandler extends AsyncTask<String, String, String>{
Command presenter;

    Public HttpRequestHandler(Object presenter){    
        this.presenter = (Command) presenter;
    }

    Public String doInBackground(String... uri){
       ...
    }

    Public onPostExecute(String result){
        presentation = new JSONObject(result);
        presenter.execute();
    }

在我看来,仅凭感觉,使用 Object 作为参数类型并不是最佳实践。我从来没有见过有人像这样使用它,而必须将给定对象转换为 Command 的想法让我误会了。有什么方法可以使 class 类型的 信任 我给它一个 Command 对象吗?

这是我第一次使用命令模式,我还没有完全理解它。温柔一点。

更新

看来我想在这里使用泛型。不过,我仍然真的不知道如何以最佳实践方式执行它。我现在拥有的是:

Command presenter; 

public <Command> HttpRequestHandler(Command presenter){
    this.presenter = (com.example.myproject.Command) presenter;
    //ugly!
}

这工作得很好我似乎可以将 Command 的任何旧实现传递给它,我似乎无法在网上找到任何具有相同语法或功能的参考。我听说过一些关于工厂模式的提及,但我感觉命令模式并不依赖于另一种模式来像这样完全发挥作用。任何方向将不胜感激。

确实是泛型的问题。 Using Bounded Type Parameters 并通过 T 扩展 Command,我可以确保我的参数将是 Command

的子类(在本例中为实现)

HttpRequestHandler 现在应该看起来像这样

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

    Command presenter;

    public <T extends Command> HttpRequestHandler(T presenter){
        this.presenter =  presenter;
    }

    presenter.execute("Success!");
}

不需要可怕的铸造。