dart_in_action/40_design_pattern_front_con...

81 lines
1.9 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
前端控制器模式Front Controller Pattern
前端控制器Front Controller - 处理应用程序所有类型请求的单个处理程序应用程序可以是基于web的应用程序也可以是非web的应用程序。
调度器Dispatcher - 前端控制器可能使用一个调度器对象来调度请求到相应的具体处理程序。
视图View - 视图是为请求而创建的对象。
*/
main(List<String> args) {
// 用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。
// 该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
//////////////////////////////////////////////////////////////////
///
/// 创建视图
///
class HomeView {
void show() {
print("Displaying Home Page");
}
}
class StudentView {
void show() {
print("Displaying Student Page");
}
}
///
/// 创建调度器 Dispatcher
///
class Dispatcher {
StudentView _studentView;
HomeView _homeView;
Dispatcher() {
_studentView = StudentView();
_homeView = HomeView();
}
void dispatch(String request) {
if (request.toUpperCase() == "STUDENT") {
_studentView.show();
} else {
_homeView.show();
}
}
}
///
/// 创建前端控制器 FrontController
///
class FrontController {
Dispatcher _dispatcher;
FrontController() {
_dispatcher = Dispatcher();
}
bool _isAuthenticUser() {
print("User is authenticated successfully.");
return true;
}
void _trackRequest(String request) {
print("Page requested: " + request);
}
void dispatchRequest(String request) {
//记录每一个请求
_trackRequest(request);
//对用户进行身份验证
if (_isAuthenticUser()) {
_dispatcher.dispatch(request);
}
}
}