Design-pattern-front-controller-pattern
提供:Dev Guides
デザインパターン-フロントコントローラーパターン
フロントコントローラーの設計パターンは、すべてのリクエストが単一のハンドラーによって処理されるように、集中化されたリクエスト処理メカニズムを提供するために使用されます。 このハンドラーは、要求の認証/承認/ログ記録または追跡を行い、対応するハンドラーに要求を渡すことができます。 以下は、このタイプのデザインパターンのエンティティです。
- フロントコントローラー-アプリケーション(Webベース/デスクトップベース)に送信されるすべての種類の要求に対する単一のハンドラー。
- Dispatcher -フロントコントローラーは、対応する特定のハンドラーに要求をディスパッチできるディスパッチャーオブジェクトを使用できます。
- View -ビューは、リクエストが行われるオブジェクトです。
実装
_FrontController_と_Dispatcher_を作成して、フロントコントローラーとDispatcherとして対応するように機能させます。 _HomeView_および_StudentView_は、リクエストがフロントコントローラーに届くさまざまなビューを表します。
デモクラス_FrontControllerPatternDemo_は、_FrontController_を使用して、フロントコントローラーの設計パターンを示します。
ステップ1
ビューを作成します。
HomeView.java
public class HomeView {
public void show(){
System.out.println("Displaying Home Page");
}
}
StudentView.java
public class StudentView {
public void show(){
System.out.println("Displaying Student Page");
}
}
ステップ2
ディスパッチャを作成します。
Dispatcher.java
public class Dispatcher {
private StudentView studentView;
private HomeView homeView;
public Dispatcher(){
studentView = new StudentView();
homeView = new HomeView();
}
public void dispatch(String request){
if(request.equalsIgnoreCase("STUDENT")){
studentView.show();
}
else{
homeView.show();
}
}
}
ステップ3
FrontControllerを作成する
FrontController.java
public class FrontController {
private Dispatcher dispatcher;
public FrontController(){
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){
//log each request
trackRequest(request);
//authenticate the user
if(isAuthenticUser()){
dispatcher.dispatch(request);
}
}
}
ステップ4
_FrontController_を使用して、フロントコントローラーの設計パターンを示します。
FrontControllerPatternDemo.java
public class FrontControllerPatternDemo {
public static void main(String[] args) {
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
}
ステップ5
出力を確認します。
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page