众所周知现在的前端模板有很多,像JSP,FreeMarker,Velocity等。
面向对象的程序设计要遵守六大设计原则之一的开闭原则,即对扩展开放——对修改关闭。
所以view层的代码,在我这里的核心在于策略模式的实现。
首先,我们写一个view层的接口
package viewTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelWrapper.Model;
public interface IView {
void viewRender(Model m,HttpServletRequest req,HttpServletResponse resp);
}
然后,依照策略模式,我们需要定义一个“锦囊”来放置各种策略。
package viewTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelWrapper.Model;
public class ViewContext {
//这里用来放置需要的view
private IView view;
//属性注入
public ViewContext(IView view){
this.view=view;
}
public void render(Model m,HttpServletRequest req,HttpServletResponse resp){
view.viewRender(m,req, resp);
}
}
接下来,我们书写JSP的view形式的代码
package viewTemplate;
import java.io.IOException;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelWrapper.Model;
public class Jsp implements IView {
@Override
public void viewRender(Model model,HttpServletRequest req, HttpServletResponse resp) {
if(model!=null){
Set<String> keys=model.getModel().keySet();
for(String key:keys){
req.setAttribute(key, model.getModel().get(key));
}
}
try {
req.getRequestDispatcher(model.getView()).forward(req, resp);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
}
}
然后,是FreeMarker和velocity的代码。我懒得去写了,你们自己填空吧,当然也可以自己去扩展IView接口去实现其他你们喜欢的模板,哈哈。
package viewTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelWrapper.Model;
public class FreeMarker implements IView {
@Override
public void viewRender(Model m,HttpServletRequest req, HttpServletResponse resp) {
}
}
package viewTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelWrapper.Model;
public class Velocity implements IView {
@Override
public void viewRender(Model m,HttpServletRequest req, HttpServletResponse resp) {
}
}
最后还没完,我们需要建立一个工厂来维护这些类
package viewTemplate;
public class ViewFactory {
//工厂模式
public static ViewContext getView(IView view){
return new ViewContext(view);
}
public static Jsp getJsp(){
return new Jsp();
}
public static FreeMarker getFreeMarker(){
return new FreeMarker();
}
public static Velocity getVelocity(){
return new Velocity();
}
}