三十、前端控制器模式
前端控制器模式(Front Controller Pattern),主要用于集中统一化对外的请求接口,便于更好的封装内部逻辑。
实现
创建不同的View视图类HomeView
,StudnetView
,模拟不同的请求反馈,创建一个前端控制器类,FrontController
,一个逻辑分发类Dispatcher
。
-
View视图类
HomeView.java
package patterns.front; /** * Created by lenovo on 2016/12/12 0012. * 创建视图类 */ public class HomeView { public void show(){ System.out.println("显示Home主页"); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
StudentView.java
package patterns.front; /** * Created by lenovo on 2016/12/12 0012. * 创建视图类 */ public class StudentView { public void show(){ System.out.println("Student 页面"); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
-
分发类
Dispatcher.java
package patterns.front; /** * Created by lenovo on 2016/12/12 0012. * 调度器,用于分配请求 */ public class Dispatcher { private HomeView homeView; private StudentView studentView; public Dispatcher() { studentView = new StudentView(); homeView = new HomeView(); } public void dispatch(String request){ if (request.equalsIgnoreCase("student")){ studentView.show(); }else { homeView.show(); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
-
前端控制器类
FrontController.java
package patterns.front; /** * Created by lenovo on 2016/12/12 0012. * 前端控制器,统一接收请求。 */ public class FrontController { private Dispatcher dispatcher; public FrontController() { dispatcher = new Dispatcher(); } private boolean isAuthenticUser(){ System.out.println("User is authenticated successfully ."); return true; } private void trackRequest(String request){ System.out.println("请求页面: "+request); } public void dispatchRequest(String request){ //记录请求 trackRequest(request); //校验用户 if (isAuthenticUser()){ dispatcher.dispatch(request); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
-
演示
FrontControllerPatternDemo.java
package patterns.front; /** * Created by lenovo on 2016/12/12 0012. * 演示 */ public class FrontControllerPatternDemo { public static void main(String[] args){ FrontController controller = new FrontController(); controller.dispatchRequest("HOME"); controller.dispatchRequest("student"); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
-
输出
请求页面: HOME User is authenticated successfully . 显示Home主页 请求页面: student User is authenticated successfully . Student 页面