ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด (Factory Method)
- ๊ณตํต ๋ก์ง์ ๋ถ๋ชจ ํด๋์ค์ ์ ์ํ๊ณ , ๋ณํ๋ ๋ถ๋ถ์ ์์ ํด๋์ค์ ๊ตฌํ
// ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด
// : ๊ฐ์ฒด ์์ฑ์ ์๋ธํด๋์ค์ ๋งก๊ธฐ๊ณ , ํด๋ผ์ด์ธํธ ํ์
๋ง ์ง์
public class FactoryMethod {
public static void main(String[] args) {
Notification noti = NotificationFactory.create("email");
noti.send("Hello, Factory!");
}
}
//์๋ฆผ(Notification) ์ธํฐํ์ด์ค => ํด๋ผ์ด์ธํธ ํ์
๋ง ์ง์
interface Notification {
void send(String message);
}
class EmailNotification implements Notification {
public void send(String message) {
System.out.println("Email: " + message);
}
}
class SmsNotification implements Notification {
public void send(String message) {
System.out.println("SMS: " + message);
}
}
//์๋ฆผ(NotificationFactory) ์๋ธ ํด๋์ค => ๊ฐ์ฒด ์์ฑ
class NotificationFactory {
public static Notification create(String type) {
return switch(type) {
case "email" -> new EmailNotification();
case "sms" -> new SmsNotification();
default -> throw new IllegalArgumentException("Unexpected value: " + type);
};
}
}
๋ค๋ฅธ ์์
// 1. ํ
ํ๋ฆฟ ์ถ์ ํด๋์ค
public abstract class PostHandlerTemplate {
// ํ
ํ๋ฆฟ ๋ฉ์๋(๋ณ๊ฒฝ ๋ถ๊ฐ, ์คํ ์์ ๊ณ ์ )
public final void handlePost(String title) {
validate(title); // ๊ณตํต ์ฒ๋ฆฌ
save(title); // ๊ฐ๋ณ ์ฒ๋ฆฌ(์ถ์๋ฉ์๋)
notifyUsers(title); // ๊ณตํต ์ฒ๋ฆฌ
}
protected void validate(String title) {
if(title == null || title.isEmpty()) {
throw new IllegalArgumentException("์ ๋ชฉ ํ์");
}
}
// ํ์(์์) ํด๋์ค์์ ๊ตฌํํด์ผ ํ ๋ถ๋ถ
protected abstract void save(String title);
protected void notifyUsers(String title) {
System.out.println("์ ๊ฒ์๊ธ ์๋ฆผ : " + title);
}
}
// 2. ์์ํด๋์ค - ํ
์คํธ ๊ฒ์๊ธ ์ ์ฅ ๋ฐฉ์ ๊ตฌํ
@Component
public class TextPostHandler extends PostHandlerTemplate{
protected void save(String title) {
System.out.println("ํ
์คํธ ๊ฒ์๊ธ ์ ์ฅ : " + title);
}
}
@RestController
public class PostController {
//์์กด์ฑ ์ถ๊ฐ
private final TextPostHandler textPostHandler;
public PostController(TextPostHandler textPostHandler) {
this.textPostHandler = textPostHandler;
}
@PostMapping("/text-post")
public String post(@RequestParam String title) {
textPostHandler.handlePost(title);
return "์์ฑ์๋ฃ";
}
}
'๋ฐฑ์๋(Back-End) ๊ฐ๋ฐ > Java' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA] ๋์์ธ ํจํด - ํ๋ก์ ํจํด(Proxy) (0) | 2025.05.28 |
---|---|
[JAVA] ๋์์ธ ํจํด - ์ ๋ต ํจํด (Strategy) (0) | 2025.05.28 |
[JAVA] ๋์์ธ ํจํด - ๋ธ๋ฆฟ์ง ํจํด(Bridge) (0) | 2025.05.28 |
[JAVA] ๋์์ธ ํจํด - ์ฑ๊ธํด ํจํด(Singleton) (0) | 2025.05.28 |
์๋ฐ ๋ฒ์ ์ ๋ฆฌ (8,11,17,21) (0) | 2025.03.19 |