๋ฐฑ์—”๋“œ(Back-End) ๊ฐœ๋ฐœ/Java

[JAVA] ๋””์ž์ธ ํŒจํ„ด - ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ ํŒจํ„ด (Factory Method)

rabo93 2025. 5. 28. 13:18

ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ ํŒจํ„ด (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 "์ž‘์„ฑ์™„๋ฃŒ";
	}
	
}