设计模式30 - 前端控制器模式

作者:billy
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处

前端控制器模式

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

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

UML结构图

在这里插入图片描述

代码实现

homeview.h
创建视图1

#include <iostream>
using namespace std;

class HomeView {
public:
    void show()
    {
        cout << "Displaying Home Page" << endl;
    }
};

studentview.h
创建视图2

#include <iostream>
using namespace std;

class StudentView
{
public:
    void show()
    {
        cout << "Displaying Student Page" << endl;
    }
};

dispatcher.h
创建调度器

#include "studentview.h"
#include "homeview.h"
#include <string>

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

    void dispatch(string request)
    {
        if("STUDENT" == request)
        {
            studentView->show();
        }
        else
        {
            homeView->show();
        }
    }

private:
    StudentView *studentView;
    HomeView *homeView;
};

frontcontroller.h
创建前端控制器

#include "dispatcher.h"

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

    void dispatchRequest(string request)
    {
        trackRequest(request);  //记录每一个请求

        if ( isAuthenticUser() )    //对用户进行身份验证
        {
            dispatcher->dispatch(request);
        }
    }

private:
    Dispatcher *dispatcher;

    bool isAuthenticUser()
    {
        cout << "User is authenticated successfully." << endl;
        return true;
    }

    void trackRequest(string request)
    {
        cout <<  "Page requested: " + request << endl;
    }
};

main.cpp
实例应用 - 使用 FrontController 来演示前端控制器设计模式

#include "frontcontroller.h"

int main()
{
    FrontController *frontController = new FrontController();
    frontController->dispatchRequest("HOME");
    cout << endl;
    frontController->dispatchRequest("STUDENT");

    return 0;
}

运行结果:
Page requested: HOME
User is authenticated successfully.
Displaying Home Page

Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page
发布了61 篇原创文章 · 获赞 218 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_34139994/article/details/96590436