使用 libGDX 的 HttpResponseListener 的 OO 设计

OO Design for using libGDX's HttpResponseListener

我有很多不同的 http 调用要调用,并且一直在为每个调用构建自定义侦听器。除了 handleHttpResponse 中的一两个方法调用外,侦听器都是相同的。所以每次都会重写以下大部分内容:

 HttpResponseListener listener = new HttpResponseListener() {
         String status;
            public void handleHttpResponse(HttpResponse httpResponse) {
                getSession(httpResponse);
                String result = httpResponse.getResultAsString();
                if (result != null) {
                    getNeeds(result);   //  <== unique part
                }
                System.out.println("Network Response:: Success");
            }
     
            public void failed(Throwable t) {
                    status = "fail";
                    System.out.println("Network Response:: [Fail] " + status);
                    t.printStackTrace();
            }

            @Override
            public void cancelled() {
                status = "cancelled";
                System.out.println("[getNeedType()] Network Response:: [Cancelled] " + status);
            }
     };

如何从所有这些重复的重新粘贴中整理我的代码?在 javadoc 中它说到:

Passing data to the * rendering thread should be done using {@link Application#postRunnable(java.lang.Runnable runnable)}

之前没有使用过可运行对象,但我认为它们是要执行的自定义逻辑块。尽管有 'post' 前缀,但我看不到如何将可运行对象附加到侦听器执行的末尾。我正在考虑扩展 HttpResponseListener 以接受 Runnable 作为参数,然后在我返回结果时在 handleHttpResponse 中调用 Runnable 块。但是如何将结果字符串传递给可运行对象呢? Runnables 看不到任何参数。您是否也扩展可运行对象来这样做?

你创建了一个新的摘要 class 来实现 HttpResponseListener。按照您使用的方式实现已取消、handleHttpResponse 和失败的方法,将抽象方法 getNeeds 添加到您的 class.

从现在开始,使用你的新摘要class。