Front Controller Pattern
前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。
- 前端控制器(Front Controller):
处理应用程序所有类型请求的单个处理程序。 - 调度器(dispatch)
前端控制器可能使用一个调度器对象来调度请求到相应的具体处理程序; - 视图(View)
视图是为请求而创建的对象。
Demo
#include<iostream>
#include<string>
using namespace std;
//创建视图类HomeView
class HomeView
{
public:
HomeView() {};
~HomeView() {};
void show();
};
void HomeView::show()
{
cout << "Displaying home page" << endl;
}
//创建视图类StudentView
class StudentView
{
public:
StudentView() {};
~StudentView() {};
void show();
};
void StudentView::show()
{
cout << "Displaying Student page" << endl;
}
//创建一个调度器类Dispatcher
class Dispatcher
{
public:
Dispatcher();
~Dispatcher();
void dispatch(string request);
private:
StudentView *studentview;
HomeView *homeview;
};
Dispatcher::Dispatcher()
{
this->studentview = new StudentView();
this->homeview = new HomeView();
}
Dispatcher::~Dispatcher()
{
delete this->studentview;
this->studentview = NULL;
delete this->homeview;
this->homeview = NULL;
}
void Dispatcher::dispatch(string request)
{
if ("student" == request)
{
this->studentview->show();
}
else
{
this->homeview->show();
}
}
//创建一个前端控制器类FrontController
class FrontController
{
public:
FrontController();
~FrontController();
bool isAuthenticUser();
void trackRequest(string request);
void dispatchRequest(string request);
private:
Dispatcher *dispatcher;
};
FrontController::FrontController()
{
this->dispatcher = new Dispatcher();
}
FrontController::~FrontController()
{
delete this->dispatcher;
this->dispatcher = NULL;
}
bool FrontController::isAuthenticUser()
{
cout << "User is authenticated successfully." << endl;
return true;
}
void FrontController::trackRequest(string request)
{
cout << "Page requested: " << request << endl;
}
void FrontController::dispatchRequest(string request)
{
trackRequest(request);
if (isAuthenticUser())
{
this->dispatcher->dispatch(request);
}
}
int main()
{
FrontController *fronController = new FrontController();
fronController->dispatchRequest("home");
fronController->dispatchRequest("student");
delete fronController;
fronController = NULL;
system("pause");
return 0;
}
- output
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page