πΎ [CS] μ λ΅ ν¨ν΄(Strategy pattern)
1οΈβ£ μ λ΅ ν¨ν΄(Strategy pattern)
- μ λ΅ ν¨ν΄(Strategy pattern) μ μ μ± ν¨ν΄(Policy pattern) μ΄λΌκ³ λ νλ©°, κ°μ±μ νμλ₯Ό λ°κΎΈκ³ μΆμ κ²½μ° βμ§μ β μμ νμ§ μκ³ μ λ΅μ΄λΌκ³ λΆλ₯΄λ βμΊ‘μνν μκ³ λ¦¬μ¦β μ 컨ν μ€νΈ μμμ λ°κΏμ£Όλ©΄μ μνΈ κ΅μ²΄κ° κ°λ₯νκ² λ§λλ ν¨ν΄μ λλ€.
- μλμ μμ μ½λλ μ°λ¦¬κ° μ΄λ€ κ²μ μ΄ λ λ€μ΄λ²νμ΄, μΉ΄μΉ΄μ€νμ΄ λ± λ€μν λ°©λ²μΌλ‘ κ²°μ νλ―μ΄ μ΄λ€ μμ΄ν
μ μ΄ λ
LUNACard
λ‘ μ¬λ κ²κ³ΌKAKAOCard
λ‘ μ¬λ κ²μ ꡬνν μμ μ λλ€.- κ²°μ λ°©μμ βμ λ΅β λ§ λ°κΏμ λ κ°μ§ λ°©μμΌλ‘ κ²°μ νλ κ²μ ꡬννμ΅λλ€.
// PaymentStrategy - interface
public interface PaymentStrategy {
void pay(int amount);
}
// KAKAOCardStrategy
public class KAKAOCardStrategy implements PaymentStrategy{
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public KAKAOCardStrategy(String name, String cardNumber, String cvv, String dateOfExpiry) {
this.name = name;
this.cardNumber = cardNumber;
this.cvv = cvv;
this.dateOfExpiry = dateOfExpiry;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid using KAKAOCard.");
}
}
// LUNACardStrategy
public class LUNACardStrategy implements PaymentStrategy {
private String emailId;
private String password;
public LUNACardStrategy(String emailId, String password) {
this.emailId = emailId;
this.password = password;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid using LUNACard");
}
}
// Item
public class Item {
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
// ShoppingCart
import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
List<Item> items;
public ShoppingCart() {
this.items = new ArrayList<>();
}
public void addItem(Item item) {
this.items.add(item);
}
public void removeItem(Item item) {
this.items.remove(item);
}
public int calculateTotal() {
int sum = 0;
for (Item item : items) {
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy pamentMethod) {
int amount = calculateTotal();
pamentMethod.pay(amount);
}
}
// Main
import designPattern.strategy.Item;
import designPattern.strategy.KAKAOCardStrategy;
import designPattern.strategy.LUNACardStrategy;
import designPattern.strategy.ShoppingCart;
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item A = new Item("A", 100);
Item B = new Item("B", 300);
cart.addItem(A);
cart.addItem(B);
// pay by LUNACard
cart.pay(new LUNACardStrategy("kobe@google.com", "1234"));
// pay by KAKAOCard
cart.pay(new KAKAOCardStrategy("Minseong Kang", "123456789", "123", "12/01"));
}
}
μ€ν κ²°κ³Ό
400 paid using LUNACard
400 paid using KAKAOCard.
- μ μ½λλ μΌν μΉ΄λμ μμ΄ν
μ λ΄μ
LUNACard
λλKAKAOCard
λΌλ λ κ°μ μ λ΅μΌλ‘ κ²°μ νλ μ½λμ λλ€.
μ©μ΄ : 컨ν μ€νΈ
νλ‘κ·Έλλ°μμμ 컨ν μ€νΈλ μν©, λ§₯λ½, λ¬Έλ§₯μ μλ―Ένλ©° κ°λ°μκ° μ΄λ ν μμ μ μλ£νλ λ° νμν λͺ¨λ κ΄λ ¨ μ 보λ₯Ό λ§ν©λλ€.