设计模式之前端控制器模式(Front Controller Pattern)

前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。以下是这种设计模式的实体。
前端控制器(Front Controller) - 处理应用程序所有类型请求的单个处理程序,应用程序可以是基于 web 的应用程序,也可以是基于桌面的应用程序。
调度器(Dispatcher) - 前端控制器可能使用一个调度器对象来调度请求到相应的具体处理程序。
视图(View) - 视图是为请求而创建的对象。
代码:
1.视图 home student

//前端控制器接收到的请求而创建的视图
public class HomeView {
    public void show() {
        System.out.println("Displaying Home Page.");
    }
}
//前端控制器接收到的请求而创建的视图
public class StudentView {
    public void show() {
        System.out.println("Displaying student page.");
    }
}

2.调度器

public class Dispatcher {
    private HomeView homeView;
    private StudentView studentView;
    public Dispatcher() {
        this.homeView=new HomeView();
        this.studentView=new StudentView();
    }
    public void dispatch(String request) {
        if("student".equalsIgnoreCase(request))
            studentView.show();
        else
            homeView.show();
    }
}

3.前端控制器

//前端控制器
public class FrontController {
    private Dispatcher dispatcher;
    
    public FrontController() {
        this.dispatcher=new Dispatcher();
    }
    //身份验证
    private boolean isAuthenticUser() {
        System.out.println("User is authenticated successfully.");
        return true;
    }
    //记录请求 相当于日志
    private void trackRequest(String request) {
        System.out.println("Page requested "+request);
    }
    
    public  void dispatchRequest(String request) {
        trackRequest(request);
        if(isAuthenticUser()) {
            dispatcher.dispatch(request);
        }
    }
    
}

4.测试

public class Test {
    public static void main(String[] args) {
        FrontController controller=new FrontController();
        controller.dispatchRequest("home");
        controller.dispatchRequest("student");
    }
}

5.测试结果

Page requested home
User is authenticated successfully.
Displaying Home Page.
Page requested student
User is authenticated successfully.
Displaying student page.

6.结论
一个请求到前端控制器,然后调用调度器进行调度。

转载于:
http://www.runoob.com/design-pattern/front-controller-pattern.html

猜你喜欢

转载自blog.csdn.net/weixin_43671840/article/details/84622319
今日推荐