front controller ๋ฐฉ์ ๋ก๊ทธ์ธ ๋ฉ์๋ ๊ตฌํํ๋ ์๋ฐ ์ฝ๋
Front Controller ํจํด์ ์ฌ์ฉํ์ฌ ๋ก๊ทธ์ธ ๋ฉ์๋๋ฅผ ๊ตฌํํ๋ Java ์ฝ๋
๋ค์๊ณผ ๊ฐ์ ํด๋์ค๋ฅผ ์์ฑํ ๊ฒ
- FrontController: ๋ชจ๋ ์์ฒญ์ ์ฒ๋ฆฌํ๋ ๋ฉ์ธ ํด๋์ค.
- Controller: ๊ฐ ์์ฒญ์ ์ฒ๋ฆฌํ๋ ์ธํฐํ์ด์ค.
- LoginController: ๋ก๊ทธ์ธ ์์ฒญ์ ์ฒ๋ฆฌํ๋ ํด๋์ค.
- Request: ํด๋ผ์ด์ธํธ์ ์์ฒญ์ ๋ํ๋ด๋ ํด๋์ค.
- Response: ํด๋ผ์ด์ธํธ์ ๋ํ ์๋ต์ ๋ํ๋ด๋ ํด๋์ค.
// Request.java
class Request {
private String action;
public Request(String action) {
this.action = action;
}
public String getAction() {
return action;
}
}
// Response.java
class Response {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
// Controller.java
interface Controller {
void handleRequest(Request request, Response response);
}
// LoginController.java
class LoginController implements Controller {
@Override
public void handleRequest(Request request, Response response) {
// ๋ก๊ทธ์ธ ๋ก์ง ๊ตฌํ
if ("login".equals(request.getAction())) {
response.setMessage("๋ก๊ทธ์ธ ์ฑ๊ณต!");
} else {
response.setMessage("์๋ชป๋ ์์ฒญ์
๋๋ค.");
}
}
}
// FrontController.java
class FrontController {
private Controller loginController;
public FrontController() {
loginController = new LoginController();
}
public void dispatchRequest(Request request) {
Response response = new Response();
// ๋ก๊ทธ์ธ ์์ฒญ ์ฒ๋ฆฌ
if ("login".equals(request.getAction())) {
loginController.handleRequest(request, response);
} else {
response.setMessage("์ฒ๋ฆฌํ ์ ์๋ ์์ฒญ์
๋๋ค.");
}
// ์๋ต ์ถ๋ ฅ
System.out.println(response.getMessage());
}
}
// Main.java
public class Main {
public static void main(String[] args) {
FrontController frontController = new FrontController();
// ๋ก๊ทธ์ธ ์์ฒญ
Request loginRequest = new Request("login");
frontController.dispatchRequest(loginRequest);
// ์๋ชป๋ ์์ฒญ
Request invalidRequest = new Request("invalid");
frontController.dispatchRequest(invalidRequest);
}
}
์ฝ๋ ์ค๋ช
- Request: ํด๋ผ์ด์ธํธ์ ์์ฒญ์ ์ ์ํ๋ ํด๋์ค
- Response: ์๋ฒ์ ์๋ต ๋ฉ์์ง๋ฅผ ์ ์ํ๋ ํด๋์ค
- Controller: ์์ฒญ์ ์ฒ๋ฆฌํ๋ ์ธํฐํ์ด์ค๋ก, ๊ฐ ์์ฒญ์ ์ฒ๋ฆฌํ๋ ๊ตฌ์ฒด์ ์ธ ํด๋์ค๋ฅผ ์ ์ํ ์ ์์
- LoginController: ๋ก๊ทธ์ธ ์์ฒญ์ ์ฒ๋ฆฌํ๋ ํด๋์ค์ ๋๋ค. ์์ฒญ์ด "login"์ธ ๊ฒฝ์ฐ ์ฑ๊ณต ๋ฉ์์ง๋ฅผ ๋ฐํ
- FrontController: ๋ชจ๋ ์์ฒญ์ ๋ฐ์ ์ ์ ํ ์ปจํธ๋กค๋ฌ์ ์ ๋ฌํ๋ ํด๋์ค
์คํ
์์ ์ฝ๋๋ฅผ Main ํด๋์ค๋ฅผ ํตํด ์คํํ๋ฉด, "๋ก๊ทธ์ธ ์ฑ๊ณต!" ๋ฐ "์ฒ๋ฆฌํ ์ ์๋ ์์ฒญ์ ๋๋ค."๋ผ๋ ๋ฉ์์ง๊ฐ ์ถ๋ ฅ
์ด ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ์ฌ ๋ค๋ฅธ ์์ฒญ๋ ์ถ๊ฐ ๊ฐ๋ฅ