Need help with Java design of Http Requester

試著忘記壹切 提交于 2019-12-11 02:05:43

问题


I am running into a design problem. I have the following (pertinent) classes:

 class LoginScreen {
   public login() {
      httpRequest = factory.createHttpRequest(url, method, this);
      httpRequest.start();
   }
   public authorize() {
      httpRequest = factory.createHttpRequest(url, method, this);
      httpRequest.start();
   }
   public requestSucceeded(){...}
   public requestFailed(){...}
 }

class HttpRequest extends Thread {

   LoginScreen screen;
   ...

   public HttpRequest(url, method, screen) {
      this.url = url;
      this.method = method;
      this.screen = screen
   }

   public run() {
     ...
   }
}

As you can see, both login() and authorize() will run the following code:

httpRequest = factory.createHttpRequest(url, method, loginScreen);
httpRequest.start();

And then, in the threaded HttpRequest class after the HttpRequest, the run() method will update LoginScreen directly with its results. For example:

screen.requestSucceeded(baos.toByteArray(), contentType);

This is proving to be a very poor design, however. I want the HttpRequest method class to be reusable in the future, and I want to be able to pass it many different types of classes, or screens. Right now, it only works with LoginScreen, and it is directly updating the LoginScreen UI.

Does anyone have any suggestions as to how I can update this design? If you could provide as much detail as possible, I'd greatly appreciate it as I have tried many different things and I keep running into problems.

Thanks!


回答1:


Have a look at Observer pattern. Here, in this case, your UI screens will be observers.



来源:https://stackoverflow.com/questions/2138100/need-help-with-java-design-of-http-requester

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!