Java前端控制器模式

x33g5p2x  于2021-09-28 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(415)

前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。以下是这种设计模式的实体。

  • 前端控制器(Front Controller) - 处理应用程序所有类型请求的单个处理程序,应用程序可以是基于 web 的应用程序,也可以是基于桌面的应用程序。
  • 调度器(Dispatcher) - 前端控制器可能使用一个调度器对象来调度请求到相应的具体处理程序。
  • 视图(View) - 视图是为请求而创建的对象。

创建视图。

  1. public class HomeView {
  2. public void show(){
  3. System.out.println("Displaying Home Page");
  4. }
  5. }
  1. public class StudentView {
  2. public void show(){
  3. System.out.println("Displaying Student Page");
  4. }
  5. }

创建调度器

  1. public class Dispatcher {
  2. private StudentView studentView;
  3. private HomeView homeView;
  4. public Dispatcher(){
  5. studentView = new StudentView();
  6. homeView = new HomeView();
  7. }
  8. public void dispatch(String request){
  9. if(request.equalsIgnoreCase("STUDENT")){
  10. studentView.show();
  11. }else{
  12. homeView.show();
  13. }
  14. }
  15. }

创建前端控制器

  1. public class FrontController {
  2. private Dispatcher dispatcher;
  3. public FrontController(){
  4. dispatcher = new Dispatcher();
  5. }
  6. private boolean isAuthenticUser(){
  7. System.out.println("User is authenticated successfully.");
  8. return true;
  9. }
  10. private void trackRequest(String request){
  11. System.out.println("Page requested: " + request);
  12. }
  13. public void dispatchRequest(String request){
  14. //记录每一个请求
  15. trackRequest(request);
  16. //对用户进行身份验证
  17. if(isAuthenticUser()){
  18. dispatcher.dispatch(request);
  19. }
  20. }
  21. }

测试

  1. public class FrontControllerPatternDemo {
  2. public static void main(String[] args) {
  3. FrontController frontController = new FrontController();
  4. frontController.dispatchRequest("HOME");
  5. System.out.println("\n\n-----------------------");
  6. frontController.dispatchRequest("STUDENT");
  7. }
  8. }

Page requested: HOME
User is authenticated successfully.
Displaying Home Page

Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page

相关文章

最新文章

更多