前端控制器模式

1.前端控制器模式简介

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

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

2.示例Demo

我们将创建 FrontController、Dispatcher 分别当作前端控制器和调度器。HomeView 和 StudentView 表示各种为前端控制器接收到的请求而创建的视图。

class HomeView {
    public void show() {
        System.out.println("Show home page");
    }
}

class StudentView {
    public void show() {
        System.out.println("Show student page");
    }
}


class Dispatcher {
    private HomeView homeView;
    private StudentView studentView;

    public Dispatcher() {
        homeView = new HomeView();
        studentView = new StudentView();
    }

    public void dispatch(String request) {
        if (request.equalsIgnoreCase("Student")) {
            studentView.show();
        } else {
            homeView.show();
        }
    }
}

class FrontController {
    private Dispatcher dispatcher;
    public FrontController() {
        dispatcher = new Dispatcher();
    }

    private boolean isAuthenticUser() {
        System.out.println("Authentication user successful");
        return true;
    }

    private void trackRequest() {
        System.out.println("Track Request");
    }

    public void dispatchRequest(String request) {
        trackRequest();
        if (isAuthenticUser()) {
            dispatcher.dispatch(request);            
        }
    }
}


class FrontControllerPatternDemo {
    public static void main(String args[]) {
        FrontController controller = new FrontController();
        controller.dispatchRequest("Student");
        controller.dispatchRequest("Home");
    }
}

参考:http://www.runoob.com/design-pattern/front-controller-pattern.html

猜你喜欢

转载自www.cnblogs.com/hellokitty2/p/10746911.html