我想问你关于mvc的问题。怎么运行的。所以,这是一个简单的例子(我不使用任何框架)
在 Controller (Servlet)中:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String page = null;
AbstractCommand action;
action = ActionFactory.getAction(request);// get command from factory
page = action.execute(request, response);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
我们为操作创建了一个通用接口(interface)(策略模式):
public interface AbstractAction {
public String execute(HttpServletRequest request, HttpServletResponse response);
}
简单操作(示例):
public class HelloAction implements AbstractAction {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) {
//....(some actions to modify request)
String page = "/main.jsp";
return page;
}
}
现在,我们的工厂:
public class ActionFactory {
private enum Actions{
HELLO;
}
public static AbstractAction getAction(HttpServletRequest request){
String action = request.getParameter("action");//take parameter from jsp
Actions actionEnum = Actions.valueOf(action.toUpperCase());
switch (actionEnum) {
case HELLO:
return new HelloAction();
}
}
}
我们来到了我迷茫的地方。 Servlet 只初始化一次,而且所有请求只初始化一次。只是将请求转发到我们修改请求或响应的操作。但是,我们为每个请求创建类的新实例。这里会发生内存溢出!?或不?
我们能否将这些操作设为静态(静态方法,一个用于所有请求)?如果两个请求同时到来,它们会发生什么?
您对此有何看法,请分享您的经验。
附言抱歉英语不好。
最佳答案
单例模式如何获取Action类的实例?
- 只需在
AbstractAction
中添加一些abstact getInstance()
方法。 - 让每个实现都提供自己的实例。
- 在每个实现类中,使用单例模式,这样只有一个实例存在。
- 确保没有操作类存储与特定请求相关的任何数据。
关于java - mvc 中的静态或非静态操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9018875/