前端控制器模式
前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。以下是这种设计模式的实体。
- 前端控制器(Front Controller) - 处理应用程序所有类型请求的单个处理程序,应用程序可以是基于 web 的应用程序,也可以是基于桌面的应用程序。
- 调度器(Dispatcher) - 前端控制器可能使用一个调度器对象来调度请求到相应的具体处理程序。
- 视图(View) - 视图是为请求而创建的对象。
前端控制器模式的实例
定义两个需要展示的页面
class HomeView {
show(){
console.log("Displaying Home Page");
}
}
class StudentView {
show(){
console.log("Displaying Student Page");
}
}定义展示器
class Dispatcher {
constructor() {
this.studentView = new StudentView();
this.homeView = new HomeView();
}
dispatch(request) {
if(request.toUpperCase()=="STUDENT"){
this.studentView.show();
}else{
this.homeView.show();
}
}
}定义前端控制器
class FrontController {
constructor(){
this.dispatcher = new Dispatcher();
}
isAuthenticUser(){
console.log("User is authenticated successfully.");
return true;
}
trackRequest(request){
console.log("Page requested: " + request);
}
dispatchRequest(request){
//记录每一个请求
this.trackRequest(request);
//对用户进行身份验证
if(this.isAuthenticUser()){
this.dispatcher.dispatch(request);
}
}
}通过前端请求,就能对所有访问的接口,进行记录和鉴权。
const frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!