public class Calculator {
public int calculate(boolean firstGuest, List<Item> items) {
int sum = 0;
for (Item item : items) {
if (firstGuest) {
sum += (int) (item.getPrice() * 0.9); // 첫 손님 10% 할인
} else if (!item.isFresh()) {
sum += (int) (item.getPrice() * 0.8); // 덜 신선한 과일 20% 할인
} else {
sum += item.getPrice();
}
}
return sum;
}
}
calculate
메서드를 수정해야함.Calculator
클래스가 할인 전략을 사용하도록 수정한다.DiscountStrategy
를 사용하여 계산을 수행하는 클래스DiscountStrategy
인터페이스
public interface DiscountStrategy {
int getDiscountPrice(Item item);
}
구체적인 전략 클래스
public class FirstGuestDiscountStrategy implements DiscountStrategy {
@Override
public int getDiscountPrice(Item item) {
return (int) (item.getPrice() * 0.9); // 10% 할인 적용
}
}
public class NonFreshItemDiscountStrategy implements DiscountStrategy {
@Override
public int getDiscountPrice(Item item) {
return (int) (item.getPrice() * 0.8); // 20% 할인 적용
}
}
계산 클래스
public class Calculator {
private DiscountStrategy discountStrategy;
public Calculator(DiscountStrategy discountStrategy) {
this.discountStrategy = discountStrategy;
}
public int calculate(List<Item> items) {
int sum = 0;
for (Item item : items) {
sum += discountStrategy.getDiscountPrice(item);
}
return sum;
}
}
public class Checkout {
public void processFirstGuestPurchase(List<Item> items) {
DiscountStrategy strategy = new FirstGuestDiscountStrategy();
Calculator calculator = new Calculator(strategy);
int total = calculator.calculate(items);
// 계산된 총액으로 결제 진행
}
}
public class Checkout {
public void processNonFreshItemsPurchase(List<Item> items) {
DiscountStrategy strategy = new NonFreshItemDiscountStrategy();
Calculator calculator = new Calculator(strategy);
int total = calculator.calculate(items);
// 계산된 총액으로 결제 진행
}
}
새로운 전략 구현
public class LastGuestDiscountStrategy implements DiscountStrategy {
@Override
public int getDiscountPrice(Item item) {
return (int) (item.getPrice() * 0.5); // 50% 할인 적용
}
}
클라이언트 코드 업데이트
public class Checkout {
public void processLastGuestPurchase(List<Item> items) {
DiscountStrategy strategy = new LastGuestDiscountStrategy();
Calculator calculator = new Calculator(strategy);
int total = calculator.calculate(items);
// 계산된 총액으로 결제 진행
}
}