Java 为web接口设计IO适配器
我有一个Java应用程序,它由一组服务组成。这些服务需要通过IOAdapter接口处理的I/O,如下所示:Java 为web接口设计IO适配器,java,design-patterns,io,adapter,Java,Design Patterns,Io,Adapter,我有一个Java应用程序,它由一组服务组成。这些服务需要通过IOAdapter接口处理的I/O,如下所示: interface IOAdapter { void info(Object arg); void error(Throwable cause); String read(String prompt); boolean confirm(String prompt); } 在服务方法中,输入是使用适配器的一些实现获得的,适配器被组合到服务实例中。然后,该适配
interface IOAdapter {
void info(Object arg);
void error(Throwable cause);
String read(String prompt);
boolean confirm(String prompt);
}
在服务方法中,输入是使用适配器的一些实现获得的,适配器被组合到服务实例中。然后,该适配器处理所有I/O(用户交互),因此允许将该关注点与实际业务逻辑分离
例如,一个典型的方法将执行以下操作:
class MyService {
IOAdapter adapter;
MyService () {
adapter = new MyAdapter(); // some implementation
}
void doSomething() {
try {
...
String val = adapter.read("Enter a value: ");
if(adapter.confirm("Are you sure?")) {
adapter.info("Value entered is: " + val);
...
} else {
doSomething();
}
} catch (Exception e) {
adapter.error(e);
...
}
}
}
现在我能够实现一个适配器,它通过Java控制台执行I/O操作。但是,如果我要提供一个通过浏览器进行I/O的基于Web的适配器的实现,有人能提出一种可能的方法吗
是否有其他方法可以帮助以更直接的方式解决此问题?如果我理解正确,您希望在自己的服务中包装HTTP服务器的功能,实现
IOAdapter
接口。我认为这在MyService
类中编写和使用interface IOAdapter
的方式上并不“漂亮”。这是因为即使您编写MyHTTPAdapter
适配器.read方法也无法使用HTTP实现
在HTTP中,我们有两个通信实体。客户端发送,服务器响应。无法使用您建议的接口对此进行建模,因为您只对一个实体进行建模,并且只有一种交换数据的方法,即方法read
。您必须改变接口设计,重点是客户机-服务器设计,然后才能包装HTTP通信
编辑:
集成两种通信模式(控制台通信和HTTP通信)不是一项简单的任务。我将提出由这个接口
强加的设计,遵循HTTP强加的客户机-服务器体系结构,假设控制台应用程序也可以实现它:
//This should be implemented by either the HTTP or the console server Adapter
interface IOAdapter {
IOResponse serveRequest(IORequest request);
}
//This interface should be implemented by both models of IOAdapter
//For example, a subclass of string could also implement this interface in
//order to unify the two models
interface IORequest {
}
//This interface should be implemented by both models of IOAdapter
//For example, a subclass of string could also implement this interface in
//order to unify the two models
interface IOResponse {
}
希望我能帮忙 您已经精确地指出了基于控制台和基于web的用例之间的架构差异。您能否建议一种替代架构/设计变更,它仍然有助于提供一个满足这两种范式的接口?或者这是不可行的,并且每个都应该有自己的方式来执行I/O?正如您在我的编辑中所看到的,我建议遵循HTTP范式,因为它比控制台范式更严格。嗯,不知道这是否适用于我的情况-我正在寻找更多的服务器端推送事件-它不需要响应客户端请求,但是从服务器端本身推送。。。