跳到主要内容

三十四、前端控制器模式(Front Controller Pattern)

前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理

该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序

前端控制器模式涉及以下实体

  • 前端控制器(Front Controller) - 处理应用程序所有类型请求的单个处理程序,应用程序可以是基于 web 的应用程序,也可以是基于桌面的应用程序。

  • 调度器(Dispatcher) - 前端控制器可能使用一个调度器对象来调度请求到相应的具体处理程序。

  • 视图(View) - 视图是为请求而创建的对象。

实现

 

1、 定义类FrontControllerDispatcher分别当作前端控制器和调度器;
2、 定义类HomeViewStudentView表示作为前端控制器接收到的请求而创建的视图;
3、 定义类FrontControllerPatternDemo使用FrontController演示前端控制器设计模式;

范例

1. 创建视图

HomeView.java

// author: pottercoding.cn 程序员波特,程序员编程资料站(pottercoding.cn)
// Copyright © 2015-2065 pottercoding.cn. All rights reserved.
package com.pottercoding.gof;
public class HomeView {
public void show(){
System.out.println("Displaying Home Page");
}

StudentView.java

// author: pottercoding.cn 程序员波特,程序员编程资料站(pottercoding.cn)
// Copyright © 2015-2065 pottercoding.cn. All rights reserved.
package com.pottercoding.gof;
public class StudentView {
public void show(){
System.out.println("Displaying Student Page");
}