这段代码取自org.glassfish.jersey.grizzly2
项目,如方法名称所示,createHttpServer
应该负责“only” 用于创建并返回 HttpServer 类的实例,我只是想知道为什么 HttpServer.start
调用要以这种方式封装?
public static HttpServer createHttpServer(final URI uri,
final GrizzlyHttpContainer handler,
final boolean secure,
final SSLEngineConfigurator sslEngineConfigurator
final boolean start) {
final String host = (uri.getHost() == null) ? NetworkListener.DEFAULT_NETWORK_HOST : uri.getHost();
final int port = (uri.getPort() == -1) ? DEFAULT_HTTP_PORT : uri.getPort();
final NetworkListener listener = new NetworkListener("grizzly", host, port);
listener.setSecure(secure);
if (sslEngineConfigurator != null) {
listener.setSSLEngineConfig(sslEngineConfigurator);
}
final HttpServer server = new HttpServer();
server.addListener(listener);
// Map the path to the processor.
final ServerConfiguration config = server.getServerConfiguration();
if (handler != null) {
config.addHttpHandler(handler, uri.getPath());
}
config.setPassTraceRequest(true);
if (start) {
try {
// Start the server.
server.start();
} catch (IOException ex) {
throw new ProcessingException(LocalizationMessages.FAILED_TO_START_SERVER(ex.getMessage()), ex);
}
}
return server;
}
最佳答案
这是一个公共(public) API 方法,而不是一个类。
Single responsibility principle in wiki说
Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class.
SRP 旨在实现松耦合和鲁棒性。它绝对可以帮助开发人员维护相同的内容,同时保持其良好运行。
所以,如果它是某种内部方法或类,我会同意的。
<小时/>公共(public)API的设计目标完全不同。
- 首先要确保易于使用。
- 您的软件还应该隐藏内部实现和设计特性。
- 如果用户正在调用此方法,并且不知道需要调用其他方法来启动,他/她会感到困惑。我们不能强制用户了解软件的整个工作流程,即手动调用每个小步骤。
希望这有帮助。
关于java - 这种违反单一责任原则的行为有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22858123/