code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,27 @@ +package christmas.system; + +public final class IOMessage { + public static final String VISIT_DATE_PROMPT_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค.\n" + + "12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"; + + public static final String ORDER_PROMPT_MESSAGE = "์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"; + + public static final String NONE = "์—†์Œ"; + public static final String EMPTY_STRING = " "; + public static final String MESSAGE_DELIMITER = ": -"; + + public static final String QUANTITY_UNIT = "๊ฐœ"; + + public static final String MONEY_UNIT = "์›"; + + public static final String XMAS_DDAY_DISCOUNT = "ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ"; + public static final String WEEKDAY_DISCOUNT = "ํ‰์ผ ํ• ์ธ"; + public static final String WEEKEND_DISCOUNT = "์ฃผ๋ง ํ• ์ธ"; + public static final String SPECIAL_DISCOUNT = "ํŠน๋ณ„ ํ• ์ธ"; + public static final String BONUS_EVENT = "์ฆ์ • ์ด๋ฒคํŠธ"; + + + private IOMessage() { + + } +}
Java
์ƒ์„ฑ์ž๋ฅผ `private`์œผ๋กœ ๋ง‰์•„๋‘์‹  ๋ชจ์Šต์ด ๋ณด๊ธฐ ์ข‹์Šต๋‹ˆ๋‹ค! ๐Ÿ˜Š
@@ -0,0 +1,54 @@ +package christmas.controller; + +import christmas.domain.entity.Day; +import christmas.domain.entity.Order; +import christmas.view.InputView; +import java.util.function.Supplier; + +import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER; +import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE; +import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE; +import static christmas.view.InputView.*; +import static christmas.view.OutputView.*; + +public class PlannerSystem { + + private final Day day; + private final Order order; + private final SettlementSystem settlementSystem; + + public PlannerSystem() { + printMessage(VISIT_DATE_PROMPT_MESSAGE); + this.day = readDay(); + printEventNotice(); + printMessage(ORDER_PROMPT_MESSAGE); + this.order = readOrder(InputView::tryReadOrder); + this.settlementSystem = new SettlementSystem(day, order); + } + public void run() { + renderResult(); + } + + private Order readOrder(Supplier<Order> orderSupplier) { + while (true) { + try { + Order order = orderSupplier.get(); + RUNTIME_VERIFIER.validate(order); + return order; + } catch (IllegalStateException e) { + printMessage(e.getMessage()); + } + } + } + + private void renderResult() { + renderPlannerResult(); + settlementSystem.renderSettlementResult(); + + } + + private void renderPlannerResult() { + printResultStartMessage(day); + printOrderList(order); + } +}
Java
static์ด ์•„๋‹ˆ๊ฒŒ ๊ตฌํ˜„ํ•ด์„œ ์˜์กด๊ด€๊ณ„๋ฅผ ๊ฐ€์ง€๊ฒŒ ํ•ด์•ผํ• ๊นŒ ๊ณ ๋ฏผํ•ด๋ดค์Šต๋‹ˆ๋‹ค. ํ™•์‹คํžˆ ์˜์กด์„ฑ ์ฃผ์ž…์ด ํ•„์š”ํ•œ ๊ด€๊ณ„์ด๋‹ค ์‹ถ์€๊ฑฐ๋Š” ์ฃผ์ž…์„ ์‹œ์ผฐ๋Š”๋ฐ inputview์™€ outputview๊นŒ์ง€ ์‹œ์ผœ์•ผํ•˜๋‚˜ ํ•ด์„œ์š”. ์‹œํ‚ค๋Š”๊ฒŒ ๋งž์„๊นŒ์š”?
@@ -0,0 +1,54 @@ +package christmas.controller; + +import christmas.domain.entity.Day; +import christmas.domain.entity.Order; +import christmas.view.InputView; +import java.util.function.Supplier; + +import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER; +import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE; +import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE; +import static christmas.view.InputView.*; +import static christmas.view.OutputView.*; + +public class PlannerSystem { + + private final Day day; + private final Order order; + private final SettlementSystem settlementSystem; + + public PlannerSystem() { + printMessage(VISIT_DATE_PROMPT_MESSAGE); + this.day = readDay(); + printEventNotice(); + printMessage(ORDER_PROMPT_MESSAGE); + this.order = readOrder(InputView::tryReadOrder); + this.settlementSystem = new SettlementSystem(day, order); + } + public void run() { + renderResult(); + } + + private Order readOrder(Supplier<Order> orderSupplier) { + while (true) { + try { + Order order = orderSupplier.get(); + RUNTIME_VERIFIER.validate(order); + return order; + } catch (IllegalStateException e) { + printMessage(e.getMessage()); + } + } + } + + private void renderResult() { + renderPlannerResult(); + settlementSystem.renderSettlementResult(); + + } + + private void renderPlannerResult() { + printResultStartMessage(day); + printOrderList(order); + } +}
Java
ํ— ๋ชฐ๋ž์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.!!
@@ -0,0 +1,32 @@ +package christmas.controller; + +import christmas.domain.entity.Day; +import christmas.domain.entity.DiscountRecord; +import christmas.domain.entity.Order; +import christmas.domain.manager.BonusEventManager; +import christmas.domain.manager.DiscountManager; + +import static christmas.domain.entity.EventBadge.createBadge; +import static christmas.view.OutputView.*; + +public class SettlementSystem { + + private final Order order; + private final DiscountRecord discountRecord; + + public SettlementSystem(Day day, Order order) { + DiscountManager discountManager = new DiscountManager(); + BonusEventManager bonusEventManager = new BonusEventManager(); + this.order = order; + this.discountRecord = DiscountRecord.create(day, order, discountManager, bonusEventManager); + } + + public void renderSettlementResult() { + printOriginalTotalAmount(order); + printBonusMenu(order); + printDiscountRecord(discountRecord); + printTotalDiscountAmount(discountRecord); + printExpectedPayment(order, discountRecord); + printEventBadge(createBadge(discountRecord)); + } +}
Java
์ด๊ฒŒ ์—ฌ๋Ÿฌ๊ฐ€์ง€๋กœ ๋‚˜๋ˆ ๋ณผ๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ ๋„ˆ๋ฌด ์–ด๋ ต๋”๋ผ๊ตฌ์š”... ๋‚˜๋ˆ ์•ผ ๊น”๋”ํ• ๊ฑฐ ๊ฐ™๊ธฐ๋Š” ํ•œ๋ฐ... ๊ทธ๋ƒฅ ์ €ํฌ๊ฐ€ plannerSystem์„ ๊ตฌํ˜„ํ•˜๋Š”๊ฑฐ์˜€๊ณ , ๊ธฐ๋Šฅ๋“ค์ด ๋‹ค ์ •์‚ฐ(๊ธˆ์œต)๊ณผ ๊ด€๋ จ๋œ ๋ถ€๋ถ„์ด๋ผ์„œ settlementSystem์„ ๋‘์—ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,76 @@ +package christmas.domain.entity; + +import static christmas.domain.verifier.VisitDateVerifier.VISIT_DATE_VERIFIER; +import static christmas.system.Constant.CHRISTMAS; +import static christmas.system.Constant.FIRST_DAY_OF_MONTH; + +public class Day { + + private static final int WEEK_LENGTH = 7; + private final int day; + + public Day(int day) { + VISIT_DATE_VERIFIER.validateInputInDomain(day); + this.day = day; + } + + public int getDay() { + return day; + } + + public boolean isChristmasSeason() { + if (day >= FIRST_DAY_OF_MONTH && day <= CHRISTMAS) { + return true; + } + return false; + } + + public boolean isWeekday() { + if (!(isFriday() || isSaturday())) { + return true; + } + return false; + } + + public boolean isWeekend() { + if (isFriday() || isSaturday()) { + return true; + } + return false; + } + + public boolean isSpecialDay() { + if (isSunday() || isChristmas()) { + return true; + } + return false; + } + + private boolean isFriday() { + if (day % WEEK_LENGTH == 1) { + return true; + } + return false; + } + + private boolean isSaturday() { + if (day % WEEK_LENGTH == 2) { + return true; + } + return false; + } + + private boolean isSunday() { + if (day % WEEK_LENGTH == 3) { + return true; + } + return false; + } + + private boolean isChristmas() { + if (day == CHRISTMAS) { + return true; + } + return false; + } +}
Java
๋ฉ”์„œ๋“œ๋ช…์„ ์ •๋ง ์ž˜ ์ง€์œผ์‹ ๊ฑฐ ๊ฐ™์•„์š”! ๐Ÿ˜
@@ -0,0 +1,48 @@ +package christmas.domain.entity; + +import christmas.domain.util.Util; + +import java.util.Arrays; + +import static christmas.system.IOMessage.EMPTY_STRING; +import static christmas.system.IOMessage.QUANTITY_UNIT; + +public enum BonusMenu { + CHAMPAGNE(Menu.CHAMPAGNE, 1); + + private final Menu menu; + private final int quantity; + + BonusMenu(Menu menu, int quantity) { + this.menu = menu; + this.quantity = quantity; + } + + public static int calculateTotalPriceForAllMenus() { + return Arrays.stream(BonusMenu.values()) + .mapToInt(BonusMenu::getTotalPrice) + .sum(); + } + + public static String generateAllMenuDetails() { + StringBuilder stringBuilder = new StringBuilder(); + for (BonusMenu bonusMenu : BonusMenu.values()) { + stringBuilder.append(bonusMenu.toString()).append(System.lineSeparator()); + } + return stringBuilder.toString(); + } + + @Override + public String toString() { + return getName() + EMPTY_STRING + Util.createFormattedAmount(quantity) + QUANTITY_UNIT; + } + + private String getName() { + return menu.getMenuName(); + } + + private int getTotalPrice() { + return menu.getMenuPrice() * quantity; + } + +}
Java
์ฒ˜์Œ์—๋Š” ๊ทธ๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ํ–ˆ์—ˆ๋Š”๋ฐ, ๊ฐ ํด๋ž˜์Šค์—์„œ, ํด๋ž˜์Šค์— ๋Œ€ํ•ด ์ถœ๋ ฅํ•  ์ •๋ณด๋ฅผ ๋งŒ๋“œ๋Š”๊ฑฐ๊นŒ์ง€๋Š” ๊ฐ์ฒด๊ฐ€ ๋‹ด๋‹นํ•ด์•ผํ•  ๋ชซ์ด์ง€ ์•Š์„๊นŒ ํ•ด์„œ ๋ฐ”๊ฟจ์—ˆ์–ด์š”... ์ถœ๋ ฅ์€ outputview์—์„œ ํ•ฉ๋‹ˆ๋‹ค. ์ด ๋ถ€๋ถ„์€ ๋‹ค๋ฅธ๋ถ€๋ถ„์˜ ์˜๊ฒฌ๋„ ๋“ฃ๊ณ  ์‹ถ์–ด์š”!! 1. outputview์—์„œ getter๊ฐ€ ์•„๋‹ˆ๋”๋ผ๋„, ์ธ์ž๋ฅผ ํ†ตํ•ด ์ถœ๋ ฅํ•  ํด๋ž˜์Šค์˜ ์ •๋ณด๋ฅผ ๊บผ๋‚ด์„œ ์ถœ๋ ฅ ๋ฉ”์‹œ์ง€๋ฅผ ๋งŒ๋“ค๊ณ  ์ถœ๋ ฅ๊นŒ์ง€ ํ•˜๋Š”๊ฑธ ๋‹ด๋‹นํ•ด์•ผํ• ๊นŒ? 2. ์ถœ๋ ฅํ•ด์•ผํ•  ํด๋ž˜์Šค์˜ ์ •๋ณด๋Š” ํด๋ž˜์Šค ๋”ด์—์„œ ๋งŒ๋“ค๊ณ , ์ถœ๋ ฅ๋งŒ outputview์—์„œ ํ•ด์•ผํ•˜๋Š”๊ฒŒ ๋งž์„๊นŒ์š”?
@@ -0,0 +1,12 @@ +package christmas.domain.util; + + +import java.text.DecimalFormat; + +public final class Util { + public static String createFormattedAmount(int target) { + DecimalFormat formatter = new DecimalFormat("###,##0"); + return formatter.format(target); + } + +}
Java
์ฐธ๊ณ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ๋„ˆ๋ฌด๋„ˆ๋ฌด ํ”ผ๋“œ๋ฐฑ ์—ด์‹ฌํžˆ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ด์š” ์˜ˆ์Šฌ๋‹˜ ๐Ÿ™ƒ
@@ -0,0 +1,76 @@ +package christmas.domain.entity; + +import static christmas.domain.verifier.VisitDateVerifier.VISIT_DATE_VERIFIER; +import static christmas.system.Constant.CHRISTMAS; +import static christmas.system.Constant.FIRST_DAY_OF_MONTH; + +public class Day { + + private static final int WEEK_LENGTH = 7; + private final int day; + + public Day(int day) { + VISIT_DATE_VERIFIER.validateInputInDomain(day); + this.day = day; + } + + public int getDay() { + return day; + } + + public boolean isChristmasSeason() { + if (day >= FIRST_DAY_OF_MONTH && day <= CHRISTMAS) { + return true; + } + return false; + } + + public boolean isWeekday() { + if (!(isFriday() || isSaturday())) { + return true; + } + return false; + } + + public boolean isWeekend() { + if (isFriday() || isSaturday()) { + return true; + } + return false; + } + + public boolean isSpecialDay() { + if (isSunday() || isChristmas()) { + return true; + } + return false; + } + + private boolean isFriday() { + if (day % WEEK_LENGTH == 1) { + return true; + } + return false; + } + + private boolean isSaturday() { + if (day % WEEK_LENGTH == 2) { + return true; + } + return false; + } + + private boolean isSunday() { + if (day % WEEK_LENGTH == 3) { + return true; + } + return false; + } + + private boolean isChristmas() { + if (day == CHRISTMAS) { + return true; + } + return false; + } +}
Java
๊ฐœ์ธ์ ์ธ ์˜๊ฒฌ์ธ๋ฐ, `isFriday() || isSaturday()`๊ฐ€ `isWeekend()`๋ฉ”์„œ๋“œ์™€ ๋˜‘๊ฐ™์œผ๋‹ˆ, ์ด๊ฑธ ํ™œ์šฉํ•˜๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”? ```java public boolean isWeekday() { return !isWeekend(); } ``` ์ด๋ ‡๊ฒŒ์š”! ๐Ÿ˜‰
@@ -0,0 +1,59 @@ +package christmas.domain.entity; + +import java.util.HashMap; +import java.util.Map; + +import static christmas.domain.entity.MenuType.*; + +public enum Menu { + + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, APPETIZER), + + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, MAIN), + + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, DESSERT), + + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3_000, BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, BEVERAGE); + + private static final Map<String, Menu> MENU_MAP = new HashMap<>(); + private final String menuName; + private final int price; + private final MenuType menuType; + + Menu(String menuName, int price, MenuType menuType) { + this.menuName = menuName; + this.price = price; + this.menuType = menuType; + } + + static { + for (Menu menu : Menu.values()) { + MENU_MAP.put(menu.menuName, menu); + } + } + + public static Menu getMenuItemByName(String menuName) { + return MENU_MAP.get(menuName); + } + + public String getMenuName() { + return menuName; + } + + public int getMenuPrice() { + return price; + } + + public MenuType getMenuType() { + return menuType; + } + +}
Java
๋”ฐ๋กœ `HashMap`์„ ๋งŒ๋“ค์–ด ๋‘” ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! `getMenuItemByName`๋ฉ”์„œ๋“œ์—์„œ ๊ฒ€์ƒ‰์†๋„๋ฅผ ๋†’์ด๊ธฐ ์œ„ํ•จ์ธ๊ฐ€์š”?
@@ -0,0 +1,12 @@ +package christmas.domain.util; + + +import java.text.DecimalFormat; + +public final class Util { + public static String createFormattedAmount(int target) { + DecimalFormat formatter = new DecimalFormat("###,##0"); + return formatter.format(target); + } + +}
Java
split์„ ํ•œ ๊ฒฐ๊ณผ๊ฐ€ ์‚ฌ์ด์ฆˆ๊ฐ€ 1์ด์–ด์„œ `orderItemSpec[1]`์˜ ์ ‘๊ทผ์ด `IndexOutOfBoundsException`์„ ์ผ์œผํ‚ฌ ๊ฒฝ์šฐ๋Š” ์—†๋‚˜์š”? ์ด๋ฅผ ์—ผ๋‘ํ•ด๋‘์…จ๋‚˜๋ฉด ์–ด๋–ป๊ฒŒ ๊ฒ€์ฆ์„ ํ•˜์…จ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,96 @@ +package christmas.domain.verifier; + + +import christmas.domain.entity.Menu; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static christmas.system.ExceptionMessage.*; + +public class OrderMenuVerifier implements Verifier<String> { + + public static final OrderMenuVerifier ORDER_MENU_VERIFIER = new OrderMenuVerifier(); + + private final Pattern pattern; + + private OrderMenuVerifier() { + this.pattern = Pattern.compile("[๊ฐ€-ํžฃ]+-\\d+(,[๊ฐ€-ํžฃ]+-\\d+)*"); + } + + @Override + public void validate(final String input) { + validateMenuFormat(input); + } + + public void validateInputInDomain(final String input) { + validateMenuExistence(input); + validateDistinctMenu(input); + validateMenuQuantity(input); + } + + private void validateMenuFormat(final String input) { + String[] orders = input.split(","); + for (String order : orders) { + validateOrderFormat(order); + } + } + + private void validateMenuExistence(final String input) { + String[] orders = input.split(","); + for (String order : orders) { + validateOrderExistence(order); + } + } + + private void validateDistinctMenu(final String input) { + Set<String> uniqueMenuItems = new HashSet<>(); + String[] orders = input.split(","); + for (String order : orders) { + validateDistinctMenu(order, uniqueMenuItems); + } + } + + private void validateMenuQuantity(final String input) { + String[] orders = input.split(","); + for (String order : orders) { + validateOrderQuantity(order); + } + } + + private void validateOrderFormat(final String order) { + Matcher matcher = pattern.matcher(order); + if (!matcher.matches()) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + private void validateOrderExistence(final String order) { + String[] orderInfo = order.split("-"); + if (Menu.getMenuItemByName(orderInfo[0]) == null) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + private void validateDistinctMenu(final String order, Set<String> uniqueMenuItems) { + String[] orderInfo = order.split("-"); + if (!uniqueMenuItems.add(orderInfo[0])) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + private void validateOrderQuantity(final String order) { + String[] orderInfo = order.split("-"); + try { + int quantity = Integer.parseInt(orderInfo[1]); + if (quantity < 1) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + +}
Java
๋”ฐ๋กœ ์ธ์ž์— ๋”ฐ๋ผ์„œ ํŒจํ„ด์ด ๋‹ฌ๋ผ์ง€๋Š” ๊ฒƒ ๊ฐ™์ง„ ์•Š์€๋ฐ, ํ•„๋“œ์—์„œ ๋ฐ”๋กœ ์ดˆ๊ธฐํ™”ํ•˜์ง€ ์•Š๊ณ , ์ƒ์„ฑ์ž ๋‚ด๋ถ€์—์„œ ์ดˆ๊ธฐํ™”ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ๋ญ๊ฐ€ ๋” ์ข‹์€ ๋ฐฉ๋ฒ•์ธ์ง€ ์ €๋„ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์š”.. ๐Ÿ˜‚
@@ -0,0 +1,14 @@ +package christmas.domain.verifier; + +public interface Verifier<T> { + + abstract public void validate(T input); + + static void throwIllegalArgumentError(String errorMessage) { + throw new IllegalArgumentException(errorMessage); + } + + static void throwIllegalStateError(String errorMessage) { + throw new IllegalStateException(errorMessage); + } +}
Java
์ด ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ํด๋ž˜์Šค๋“ค์€ `check`๋งŒ ์‚ฌ์šฉํ•˜๋ฉด ํ•„์š”ํ•œ ๊ฒ€์ฆ์ด ๋‹ค ๋˜๋Š” ๋ฐฉ์‹์ด๋„ค์š”! ๊น”๋”ํ•˜๊ณ  ์ข‹๋„ค์š”! ๐Ÿ˜Š
@@ -0,0 +1,59 @@ +package christmas.domain.entity; + +import java.util.HashMap; +import java.util.Map; + +import static christmas.domain.entity.MenuType.*; + +public enum Menu { + + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, APPETIZER), + + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, MAIN), + + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, DESSERT), + + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3_000, BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, BEVERAGE); + + private static final Map<String, Menu> MENU_MAP = new HashMap<>(); + private final String menuName; + private final int price; + private final MenuType menuType; + + Menu(String menuName, int price, MenuType menuType) { + this.menuName = menuName; + this.price = price; + this.menuType = menuType; + } + + static { + for (Menu menu : Menu.values()) { + MENU_MAP.put(menu.menuName, menu); + } + } + + public static Menu getMenuItemByName(String menuName) { + return MENU_MAP.get(menuName); + } + + public String getMenuName() { + return menuName; + } + + public int getMenuPrice() { + return price; + } + + public MenuType getMenuType() { + return menuType; + } + +}
Java
๋„ค ๋งž์•„์š”! HashMap์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ฒ€์ƒ‰์†๋„๊ฐ€ O(1)์— ๊ฐ€๊นŒ์šด ์†๋„๋กœ ๋งค์šฐ ํ–ฅ์ƒ๋œ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.!!
@@ -0,0 +1,96 @@ +package christmas.domain.verifier; + + +import christmas.domain.entity.Menu; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static christmas.system.ExceptionMessage.*; + +public class OrderMenuVerifier implements Verifier<String> { + + public static final OrderMenuVerifier ORDER_MENU_VERIFIER = new OrderMenuVerifier(); + + private final Pattern pattern; + + private OrderMenuVerifier() { + this.pattern = Pattern.compile("[๊ฐ€-ํžฃ]+-\\d+(,[๊ฐ€-ํžฃ]+-\\d+)*"); + } + + @Override + public void validate(final String input) { + validateMenuFormat(input); + } + + public void validateInputInDomain(final String input) { + validateMenuExistence(input); + validateDistinctMenu(input); + validateMenuQuantity(input); + } + + private void validateMenuFormat(final String input) { + String[] orders = input.split(","); + for (String order : orders) { + validateOrderFormat(order); + } + } + + private void validateMenuExistence(final String input) { + String[] orders = input.split(","); + for (String order : orders) { + validateOrderExistence(order); + } + } + + private void validateDistinctMenu(final String input) { + Set<String> uniqueMenuItems = new HashSet<>(); + String[] orders = input.split(","); + for (String order : orders) { + validateDistinctMenu(order, uniqueMenuItems); + } + } + + private void validateMenuQuantity(final String input) { + String[] orders = input.split(","); + for (String order : orders) { + validateOrderQuantity(order); + } + } + + private void validateOrderFormat(final String order) { + Matcher matcher = pattern.matcher(order); + if (!matcher.matches()) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + private void validateOrderExistence(final String order) { + String[] orderInfo = order.split("-"); + if (Menu.getMenuItemByName(orderInfo[0]) == null) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + private void validateDistinctMenu(final String order, Set<String> uniqueMenuItems) { + String[] orderInfo = order.split("-"); + if (!uniqueMenuItems.add(orderInfo[0])) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + private void validateOrderQuantity(final String order) { + String[] orderInfo = order.split("-"); + try { + int quantity = Integer.parseInt(orderInfo[1]); + if (quantity < 1) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE); + } + } + + +}
Java
์ €๋„ ๋ญ๊ฐ€ ๋” ์ข‹์€ ๋ฐฉ๋ฒ•์ธ์ง€ ๋ชฐ๋ผ์„œ ์ฐพ์•„๋ดค์—ˆ๋Š”๋ฐ, ์ƒ์„ฑ์ž์—์„œ ์ดˆ๊ธฐํ™”๋ฅผ ํ•˜๋ฉด, ์ƒ์„ฑ์ž ์•ˆ์˜ ํ•จ์ˆ˜์— ๋Œ€ํ•œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•ด์ง€๊ณ , ์™ธ๋ถ€์—์„œ ๋‹ค๋ฅธ pattern๊ฐ์ฒด๋ฅผ ์ฃผ์ž…ํ•˜๊ธฐ๊ฐ€ ์‰ฌ์›Œ์ง„๋‹ค๊ณ  ํ•˜๋”๋ผ๊ตฌ์š”. ๋ฐ˜๋ฉด์— ํ•„๋“œ์—์„œ ์ดˆ๊ธฐํ™”ํ•˜๋ฉด ๊ฐ€๋…์„ฑ๊ณผ ๊ฐ„๊ฒฐํ•จ์ด ์žฅ์ ์ด์ฃ . ์ƒ์„ฑ์ž์•ˆ์—์„œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๋กœ์ง์ด ์—†์ง€๋งŒ ์ด๋ ‡๊ฒŒ๋„ ํ•œ๋ฒˆ ํ•ด๋ดค์–ด์š”! ์ƒํ™ฉ์— ๋”ฐ๋ผ์„œ ๋‹ค๋ฅด๊ฒŒ ํ•ด๋ณด๋ฉด ์ข‹์„๊ฑฐ ๊ฐ™์•„์š”!!
@@ -0,0 +1,14 @@ +package christmas.domain.verifier; + +public interface Verifier<T> { + + abstract public void validate(T input); + + static void throwIllegalArgumentError(String errorMessage) { + throw new IllegalArgumentException(errorMessage); + } + + static void throwIllegalStateError(String errorMessage) { + throw new IllegalStateException(errorMessage); + } +}
Java
ํ”ผ๋“œ๋ฐฑ ์ •๋ง ๊ฐ์‚ฌํ•ด์š”! ์„ธ์›…๋‹˜๋„ ํฌ๋ฆฌ์Šค๋งˆ์Šค ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ•ด๋“œ๋ฆด๋ ค๊ณ  ํ•˜๋Š”๋ฐ repository๊ฐ€ private์ธ๊ฐ€๋ด์š”๐Ÿ˜‚
@@ -0,0 +1,76 @@ +package christmas.domain.entity; + +import static christmas.domain.verifier.VisitDateVerifier.VISIT_DATE_VERIFIER; +import static christmas.system.Constant.CHRISTMAS; +import static christmas.system.Constant.FIRST_DAY_OF_MONTH; + +public class Day { + + private static final int WEEK_LENGTH = 7; + private final int day; + + public Day(int day) { + VISIT_DATE_VERIFIER.validateInputInDomain(day); + this.day = day; + } + + public int getDay() { + return day; + } + + public boolean isChristmasSeason() { + if (day >= FIRST_DAY_OF_MONTH && day <= CHRISTMAS) { + return true; + } + return false; + } + + public boolean isWeekday() { + if (!(isFriday() || isSaturday())) { + return true; + } + return false; + } + + public boolean isWeekend() { + if (isFriday() || isSaturday()) { + return true; + } + return false; + } + + public boolean isSpecialDay() { + if (isSunday() || isChristmas()) { + return true; + } + return false; + } + + private boolean isFriday() { + if (day % WEEK_LENGTH == 1) { + return true; + } + return false; + } + + private boolean isSaturday() { + if (day % WEEK_LENGTH == 2) { + return true; + } + return false; + } + + private boolean isSunday() { + if (day % WEEK_LENGTH == 3) { + return true; + } + return false; + } + + private boolean isChristmas() { + if (day == CHRISTMAS) { + return true; + } + return false; + } +}
Java
์˜ค... ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.! ๋ฆฌํŽ™ํ† ๋ง ํ•ด๋ณผ๊ฒŒ์š”
@@ -0,0 +1,12 @@ +package christmas.domain.util; + + +import java.text.DecimalFormat; + +public final class Util { + public static String createFormattedAmount(int target) { + DecimalFormat formatter = new DecimalFormat("###,##0"); + return formatter.format(target); + } + +}
Java
์˜ˆ๋ฅผ๋“ค์–ด, Input: ์ƒดํŽ˜์ธ- ์ด๋ ‡๊ฒŒ ์ž…๋ ฅ๋œ ๊ฒฝ์šฐ, orderMenuVerifier์˜ checkMenuFormat ๋ฉ”์†Œ๋“œ์— ์˜ํ•ด ์˜ฌ๋ฐ”๋ฅธ ๋ฉ”๋‰ด ํ˜•์‹์ด ์•„๋‹Œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๊ฐ€ ๋˜์–ด์ ธ๋ฒ„๋ ค ์œ„์˜ Util๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์—†๋„๋ก ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค. <img width="474" alt="image" src="https://github.com/Hoo-sung/java-christmas-6-Hoo-sung/assets/121723421/e2a0a147-e665-4a6a-94ce-3876632e0d0b"> ์ด๋ ‡๊ฒŒ orderMenuVerifier๋กœ ๊ฒ€์ฆ์„ ๋งˆ์น˜๊ณ  Util class๋ฅผ ์ด์šฉํ•ด์„œ order๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,54 @@ +const generateBasicToken = (userId: string, userPassword: string): string => { + const token = btoa(`${userId}:${userPassword}`); + return `Basic ${token}`; +}; + +const API_URL = `${import.meta.env.VITE_API_URL}`; +const USER_ID = `${import.meta.env.VITE_USER_ID}`; +const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`; + +try { + if (!API_URL || !USER_ID || !USER_PASSWORD) { + throw new Error( + "API_URL, USER_ID, PASSWORD environment variables are not set", + ); + } +} catch (error) { + console.log(error); +} + +type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE"; + +interface RequestOptions { + method: HttpMethod; + body?: Record<string, unknown>; +} + +export const fetchWithAuth = async (path: string, options: RequestOptions) => { + const requestInit = requestBuilder(options); + const response = await fetch(path, requestInit); + + try { + if (!response.ok) { + throw new Error(`Failed to ${options.method} ${path}`); + } + } catch (error) { + console.log(error); + } + + return response; +}; + +const requestBuilder = ({ method, body }: RequestOptions): RequestInit => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const headers: HeadersInit = { + "Content-Type": "application/json", + Authorization: token, + }; + + return { + method, + headers, + body: body ? JSON.stringify(body) : undefined, + }; +};
TypeScript
``` const API_URL = `${import.meta.env.VITE_API_URL}`; const USER_ID = `${import.meta.env.VITE_USER_ID}`; const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`; ``` ์ด ๋ถ€๋ถ„์€ ์ƒ์ˆ˜ ํŒŒ์ผ์—์„œ ๋”ฐ๋กœ ๊ด€๋ฆฌํ•ด๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”? `API_URL `์ด ์•„์ด๋Š” endPoint, fetchWithAuth์—์„œ ๋‘ ๋ฒˆ ์„ ์–ธ๋˜๋„ค์š”
@@ -0,0 +1,123 @@ +import { RULE } from "@constants/rules"; +import { + CART_ITEMS_COUNTS_ENDPOINT, + CART_ITEMS_ENDPOINT, + PRODUCTS_ENDPOINT, +} from "./endpoints"; +import { fetchWithAuth } from "./fetchWithAuth"; + +/** + * @example + * const params: QueryParams = { + * category: 'fashion', + * page: 1, + * size: 20, + * sort: ['price', 'asc'] + * } + */ +interface QueryParams { + [key: string]: + | undefined + | string + | number + | boolean + | (string | number | boolean)[]; +} + +export interface GetProductsParams { + category?: Category; + page?: number; + size?: number; + sort?: Sort; +} + +const createQueryString = (params: QueryParams) => { + return Object.entries(params) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => { + if (Array.isArray(value)) { + return `${encodeURIComponent(key)}=${encodeURIComponent(value.join(","))}`; + } + return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`; + }) + .join("&"); +}; + +export const getProducts = async ({ + category, + page = 0, + size = 20, + sort = "asc", +}: GetProductsParams = {}): Promise<Product[]> => { + const params = { + category, + page, + size, + sort: ["price", sort], + }; + const queryString = createQueryString(params) + RULE.sortQueryByIdAsc; + + const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, { + method: "GET", + }); + const data = await response.json(); + + if (!response.ok) { + throw new Error("Failed to get products item"); + } + + return data.content; +}; + +export const postProductInCart = async ( + productId: number, + quantity: number = 1, +) => { + const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, { + method: "POST", + body: { + productId, + quantity, + }, + }); + + if (!response.ok) { + throw new Error("Failed to post product item in cart"); + } +}; + +export const deleteProductInCart = async (cartId: number) => { + const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, { + method: "DELETE", + }); + + if (!response.ok) { + throw new Error("Failed to delete product item in cart"); + } +}; + +export const getCartItemsCount = async (): Promise<number> => { + const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, { + method: "GET", + }); + const data = await response.json(); + + if (!response.ok) { + throw new Error("Failed to get cart items count"); + } + + return data; +}; + +export const getCartItems = async (): Promise<CartItem[]> => { + const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, { + method: "GET", + }); + const data = await response.json(); + + if (!response.ok) { + throw new Error("Failed to get cart items count"); + } + + return data.content; +};
TypeScript
์š”์ฒญํ•ด์•ผํ•˜๋Š” api ๊ฐ€ ๋งŽ์•„์ง„๋‹ค๋ฉด, api/index.ts ์ฝ”๋“œ๊ฐ€ ๋งŽ์•„์ง€๊ฒ ๋„ค์š”. ๊ด€๋ จ์žˆ๋Š” api ์š”์ฒญ ๋ผ๋ฆฌ ๋ฌถ์–ด์„œ ํŒŒ์ผ๋กœ ๊ด€๋ฆฌํ•˜๊ณ , index.ts์—์„œ ํ•ด๋‹น ํŒŒ์ผ๋“ค์˜ api ์š”์ฒญ ๋ฉ”์„œ๋“œ๋ฅผ export ํ•˜๋Š” ๊ฒƒ์„ ์–ด๋–จ๊นŒ์š”? ```dash api ใ„ด cart ใ„ด products ใ„ด index ```
@@ -0,0 +1,61 @@ +import { forwardRef, useContext } from "react"; +import * as PI from "./ProductItem.style"; +import CartControlButton from "../../Button/CartControlButton"; +import { deleteProductInCart, postProductInCart } from "@api/index"; +import { useError } from "@hooks/index"; +import { CartItemsContext } from "@context/CartItemsContext"; + +interface ProductProps { + product: Product; +} + +const ProductItem = forwardRef<HTMLDivElement, ProductProps>( + ({ product }, ref) => { + const { cartItems, refreshCartItems } = useContext(CartItemsContext); + + const cartItemIds = cartItems.map((item) => item.product.id); + const isInCart = cartItemIds.includes(product.id); + + const { showError } = useError(); + + const handleIsInCart = async () => { + try { + if (!isInCart) { + await postProductInCart(product.id); + refreshCartItems(); + return; + } + + const filteredItem = cartItems.find( + (item) => item.product.id === product.id, + ); + if (filteredItem) { + await deleteProductInCart(filteredItem.id); + refreshCartItems(); + } + } catch (error) { + if (error instanceof Error) { + showError(error.message); + } + } + }; + + return ( + <PI.ProductItemStyle ref={ref}> + <PI.ProductImg + src={`${product.imageUrl}`} + alt={`${product.name} ์ƒํ’ˆ ์ด๋ฏธ์ง€`} + /> + <PI.ProductGroup> + <PI.ProductContent> + <PI.ProductName>{product.name}</PI.ProductName> + <span>{product.price.toLocaleString("ko-kr")}์›</span> + </PI.ProductContent> + <CartControlButton onClick={handleIsInCart} isInCart={isInCart} /> + </PI.ProductGroup> + </PI.ProductItemStyle> + ); + }, +); + +export default ProductItem;
Unknown
์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ๋‹ด๋Š” ๋กœ์ง๊ณผ ๋นผ๋Š” ๋กœ์ง์„ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•˜๊ณ , if else๋Œ€์‹  early return ์„ ์‚ฌ์šฉํ•ด๋ณด๋Š” ๊ฒƒ์„ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,61 @@ +import { forwardRef, useContext } from "react"; +import * as PI from "./ProductItem.style"; +import CartControlButton from "../../Button/CartControlButton"; +import { deleteProductInCart, postProductInCart } from "@api/index"; +import { useError } from "@hooks/index"; +import { CartItemsContext } from "@context/CartItemsContext"; + +interface ProductProps { + product: Product; +} + +const ProductItem = forwardRef<HTMLDivElement, ProductProps>( + ({ product }, ref) => { + const { cartItems, refreshCartItems } = useContext(CartItemsContext); + + const cartItemIds = cartItems.map((item) => item.product.id); + const isInCart = cartItemIds.includes(product.id); + + const { showError } = useError(); + + const handleIsInCart = async () => { + try { + if (!isInCart) { + await postProductInCart(product.id); + refreshCartItems(); + return; + } + + const filteredItem = cartItems.find( + (item) => item.product.id === product.id, + ); + if (filteredItem) { + await deleteProductInCart(filteredItem.id); + refreshCartItems(); + } + } catch (error) { + if (error instanceof Error) { + showError(error.message); + } + } + }; + + return ( + <PI.ProductItemStyle ref={ref}> + <PI.ProductImg + src={`${product.imageUrl}`} + alt={`${product.name} ์ƒํ’ˆ ์ด๋ฏธ์ง€`} + /> + <PI.ProductGroup> + <PI.ProductContent> + <PI.ProductName>{product.name}</PI.ProductName> + <span>{product.price.toLocaleString("ko-kr")}์›</span> + </PI.ProductContent> + <CartControlButton onClick={handleIsInCart} isInCart={isInCart} /> + </PI.ProductGroup> + </PI.ProductItemStyle> + ); + }, +); + +export default ProductItem;
Unknown
alt์— ๋Œ€ํ•ด์„œ ์ €๋ฒˆ ๋ฏธ์…˜์—์„œ ํ•˜๋ฃจ์—๊ฒŒ ๋ฐ›์€ ํ”ผ๋“œ๋ฐฑ์„ ๊ณต์œ ํ•  ๊ฒŒ์š”. image์˜ alt๋Š” 'ํฐ ์šด๋™ํ™”์— ๊ฒ€์€์ƒ‰ ์ค„์ด ํ•˜๋‚˜ ๋“ค์–ด๊ฐ„ ์•„๋””๋‹ค์Šค ์šด๋™ํ™”'์ฒ˜๋Ÿผ ํ•ด๋‹น ์ด๋ฏธ์ง€์— ๋Œ€ํ•œ ๊ตฌ์ฒด์ ์ธ ์„ค๋ช…์ด ๋“ค์–ด๊ฐ€์•ผํ•ด์š”. ํ•˜์ง€๋งŒ ํ˜„์žฌ ์„œ๋ฒ„์—์„œ ์ฃผ๋Š” ์ž์„ธํ•œ ์ƒํ’ˆ ์„ค๋ช…์ด ์—†๋Š” ์ƒํ™ฉ์—์„œ๋Š”`alt=''"`๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ํ•˜๋„ค์š”. alt๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒƒ๊ณผ alt์„ ๋นˆ๋ฌธ์ž์—ด๋กœ ๋‘๋Š” ๊ฒƒ์˜ ์ฐจ์ด๋ฅผ ๊ณต๋ถ€ํ•ด๋ณธ๋‹ค๋ฉด, ์†Œํ•˜์—๊ฒŒ ๋„์›€์ด ๋ ๊ฑฐ์—์š”. ๐Ÿ˜†
@@ -0,0 +1,44 @@ +import { FILTER_CATEGORIES, SORT_PRICE } from "@constants/rules"; +import * as PLH from "./ProductListHeader.style"; + +interface ProductListHeaderProps { + handleCategory: (category: Category) => void; + handleSort: (sort: Sort) => void; +} + +const ProductListHeader = ({ + handleCategory, + handleSort, +}: ProductListHeaderProps) => { + return ( + <PLH.Header> + <PLH.Title>bpple ์ƒํ’ˆ ๋ชฉ๋ก</PLH.Title> + <PLH.SelectBoxGroup> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleCategory(e.target.value as Category)} + > + {Object.entries(FILTER_CATEGORIES).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleSort(e.target.value as Sort)} + > + {Object.entries(SORT_PRICE).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + </PLH.SelectBoxGroup> + </PLH.Header> + ); +}; + +export default ProductListHeader;
Unknown
selectbox ๋‘˜ ๋‹ค name,id๋ฅผ ๋นˆ๋ฌธ์ž์—ด๋กœ ๋‘” ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,44 @@ +import { FILTER_CATEGORIES, SORT_PRICE } from "@constants/rules"; +import * as PLH from "./ProductListHeader.style"; + +interface ProductListHeaderProps { + handleCategory: (category: Category) => void; + handleSort: (sort: Sort) => void; +} + +const ProductListHeader = ({ + handleCategory, + handleSort, +}: ProductListHeaderProps) => { + return ( + <PLH.Header> + <PLH.Title>bpple ์ƒํ’ˆ ๋ชฉ๋ก</PLH.Title> + <PLH.SelectBoxGroup> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleCategory(e.target.value as Category)} + > + {Object.entries(FILTER_CATEGORIES).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleSort(e.target.value as Sort)} + > + {Object.entries(SORT_PRICE).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + </PLH.SelectBoxGroup> + </PLH.Header> + ); +}; + +export default ProductListHeader;
Unknown
selectbox๋ฅผ ํ•˜๋‚˜์˜ ์ปดํฌ๋„ŒํŠธ๋กœ ๋ถ„๋ฆฌํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,54 @@ +const generateBasicToken = (userId: string, userPassword: string): string => { + const token = btoa(`${userId}:${userPassword}`); + return `Basic ${token}`; +}; + +const API_URL = `${import.meta.env.VITE_API_URL}`; +const USER_ID = `${import.meta.env.VITE_USER_ID}`; +const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`; + +try { + if (!API_URL || !USER_ID || !USER_PASSWORD) { + throw new Error( + "API_URL, USER_ID, PASSWORD environment variables are not set", + ); + } +} catch (error) { + console.log(error); +} + +type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE"; + +interface RequestOptions { + method: HttpMethod; + body?: Record<string, unknown>; +} + +export const fetchWithAuth = async (path: string, options: RequestOptions) => { + const requestInit = requestBuilder(options); + const response = await fetch(path, requestInit); + + try { + if (!response.ok) { + throw new Error(`Failed to ${options.method} ${path}`); + } + } catch (error) { + console.log(error); + } + + return response; +}; + +const requestBuilder = ({ method, body }: RequestOptions): RequestInit => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const headers: HeadersInit = { + "Content-Type": "application/json", + Authorization: token, + }; + + return { + method, + headers, + body: body ? JSON.stringify(body) : undefined, + }; +};
TypeScript
์˜ค, ๋ฐ”๋กœ ์ ๊ทน ๋ฐ˜์˜ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,61 @@ +import { forwardRef, useContext } from "react"; +import * as PI from "./ProductItem.style"; +import CartControlButton from "../../Button/CartControlButton"; +import { deleteProductInCart, postProductInCart } from "@api/index"; +import { useError } from "@hooks/index"; +import { CartItemsContext } from "@context/CartItemsContext"; + +interface ProductProps { + product: Product; +} + +const ProductItem = forwardRef<HTMLDivElement, ProductProps>( + ({ product }, ref) => { + const { cartItems, refreshCartItems } = useContext(CartItemsContext); + + const cartItemIds = cartItems.map((item) => item.product.id); + const isInCart = cartItemIds.includes(product.id); + + const { showError } = useError(); + + const handleIsInCart = async () => { + try { + if (!isInCart) { + await postProductInCart(product.id); + refreshCartItems(); + return; + } + + const filteredItem = cartItems.find( + (item) => item.product.id === product.id, + ); + if (filteredItem) { + await deleteProductInCart(filteredItem.id); + refreshCartItems(); + } + } catch (error) { + if (error instanceof Error) { + showError(error.message); + } + } + }; + + return ( + <PI.ProductItemStyle ref={ref}> + <PI.ProductImg + src={`${product.imageUrl}`} + alt={`${product.name} ์ƒํ’ˆ ์ด๋ฏธ์ง€`} + /> + <PI.ProductGroup> + <PI.ProductContent> + <PI.ProductName>{product.name}</PI.ProductName> + <span>{product.price.toLocaleString("ko-kr")}์›</span> + </PI.ProductContent> + <CartControlButton onClick={handleIsInCart} isInCart={isInCart} /> + </PI.ProductGroup> + </PI.ProductItemStyle> + ); + }, +); + +export default ProductItem;
Unknown
์ง„์งœ ์ •์„ฑ์–ด๋ฆฐ ๋‹ต๋ณ€ ์ตœ๊ณ ..
@@ -0,0 +1,44 @@ +import { FILTER_CATEGORIES, SORT_PRICE } from "@constants/rules"; +import * as PLH from "./ProductListHeader.style"; + +interface ProductListHeaderProps { + handleCategory: (category: Category) => void; + handleSort: (sort: Sort) => void; +} + +const ProductListHeader = ({ + handleCategory, + handleSort, +}: ProductListHeaderProps) => { + return ( + <PLH.Header> + <PLH.Title>bpple ์ƒํ’ˆ ๋ชฉ๋ก</PLH.Title> + <PLH.SelectBoxGroup> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleCategory(e.target.value as Category)} + > + {Object.entries(FILTER_CATEGORIES).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleSort(e.target.value as Sort)} + > + {Object.entries(SORT_PRICE).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + </PLH.SelectBoxGroup> + </PLH.Header> + ); +}; + +export default ProductListHeader;
Unknown
์•—.. ๊ทธ๊ฒƒ์€ ๋ฏธ์ฒ˜ ์ž‘์„ฑํ•˜์ง€ ๋ชปํ•œ ์ €์˜ ์‹ค์ˆ˜..
@@ -0,0 +1,44 @@ +import { FILTER_CATEGORIES, SORT_PRICE } from "@constants/rules"; +import * as PLH from "./ProductListHeader.style"; + +interface ProductListHeaderProps { + handleCategory: (category: Category) => void; + handleSort: (sort: Sort) => void; +} + +const ProductListHeader = ({ + handleCategory, + handleSort, +}: ProductListHeaderProps) => { + return ( + <PLH.Header> + <PLH.Title>bpple ์ƒํ’ˆ ๋ชฉ๋ก</PLH.Title> + <PLH.SelectBoxGroup> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleCategory(e.target.value as Category)} + > + {Object.entries(FILTER_CATEGORIES).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + <PLH.SelectBox + name="" + id="" + onChange={(e) => handleSort(e.target.value as Sort)} + > + {Object.entries(SORT_PRICE).map(([key, value]) => ( + <option value={key} key={key}> + {value} + </option> + ))} + </PLH.SelectBox> + </PLH.SelectBoxGroup> + </PLH.Header> + ); +}; + +export default ProductListHeader;
Unknown
๋”ฐ๋กœ ๋ถ„๋ฆฌํ• ๊นŒ ๊ณ ๋ฏผํ–ˆ์—ˆ๋Š”๋ฐ, ์˜๊ฒฌ์ด ๋“ค์–ด์™”์œผ๋‹ˆ ๋ถ„๋ฆฌํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,195 @@ +# https://www.acmicpc.net/problem/9663 + +# import sys +# from turtle import width +# n = int(sys.stdin.readline()) + +# all_page = [0] * n #์—ด +# a = [False] * n #ํ–‰ +# b = [False] * ((n * 2) - 1) #์ •๋ฐฉํ–ฅ ๋Œ€๊ฐ +# c = [False] * ((n * 2) - 1) #์—ญ๋ฐฉํ–ฅ ๋Œ€๊ฐ + + +# def queen(n) -> None: +# first = 0 +# count = 0 +# for i in range(n): +# print("i=",i) +# if (not a[i] +# and not b[first+i] +# and not c[first-i+(n-1)] +# ): +# print("qwe") +# count += 1 +# if i == n-1: +# print(count) +# else: +# a[i] = True +# b[i+first] = True +# c[i-first+(n-1)] = True +# queen(first+1) +# a[i] = False +# b[i+first] = False +# c[i-first+(n-1)] = False +# queen(8) + + +# import sys +# n = int(sys.stdin.readline()) + +# pos = [0] * n #์—ด +# flag_a = [False] * n #ํ–‰ +# flag_b = [False] * ((n * 2) - 1) #์ •๋ฐฉํ–ฅ ๋Œ€๊ฐ +# flag_c = [False] * ((n * 2) - 1) #์—ญ๋ฐฉํ–ฅ ๋Œ€๊ฐ +# sum = [0] + + +# def queen(i) -> None: +# for j in range(n): +# if(not flag_a[j] +# and not flag_b[i+j] +# and not flag_c[i-j+(n-1)]): +# pos[i] = j +# if i == n-1: +# # for i in range(n): +# # print(f'{pos[i]:2}', end='') +# # print() +# sum[0] += 1 +# else: +# flag_a[j] = flag_b[i+j] = flag_c[i-j+(n-1)] = True +# queen(i + 1) +# flag_a[j] = flag_b[i+j] = flag_c[i-j+(n-1)] = False +# queen(0) +# print(sum[0]) + +# import sys +# n = int(sys.stdin.readline()) + +# pos = [0] * n #์—ด +# flag_a = [False] * n #ํ–‰ +# flag_b = [False] * ((n * 2) - 1) #์ •๋ฐฉํ–ฅ ๋Œ€๊ฐ +# flag_c = [False] * ((n * 2) - 1) #์—ญ๋ฐฉํ–ฅ ๋Œ€๊ฐ +# sum = [0] + + +# def queen(i) -> None: +# for j in range(n): +# if(not flag_a[j] +# and not flag_b[i+j] +# and not flag_c[i-j+7]): +# pos[i] = j +# if i == 7: +# # for i in range(8): +# # print(f'{pos[i]:2}', end='') +# # print() +# sum[0] += 1 +# else: +# flag_a[j] = flag_b[i+j] = flag_c[i-j+7] = True +# queen(i + 1) +# flag_a[j] = flag_b[i+j] = flag_c[i-j+7] = False +# queen(0) +# print(sum[0]) + +# https://seongonion.tistory.com/103 +# import sys + +# n = int(sys.stdin.readline()) + +# ans = 0 +# row = [0] * n + +# def is_promising(x): +# for i in range(x): +# if row[x] == row[i] or abs(row[x] - row[i]) == abs(x - i): +# return False + +# return True + +# def n_queens(x): +# global ans +# if x == n: +# ans += 1 +# return + +# else: +# for i in range(n): +# # [x, i]์— ํ€ธ์„ ๋†“๊ฒ ๋‹ค. +# row[x] = i +# if is_promising(x): +# n_queens(x+1) + +# n_queens(0) +# print(ans) + +# https://velog.io/@inhwa1025/BOJ-9663%EB%B2%88-N-Queen-Python-%ED%8C%8C%EC%9D%B4%EC%8D%AC + +# n = int(input()) +# result = 0 + + +# # ํ€ธ์„ ๋†“์€ ํ›„ ๊ทธ ์ดํ›„์˜ ์ค„์— ๋Œ€ํ•ด์„œ๋งŒ ๋ถˆ๊ฐ€๋Šฅํ•œ ์นธ ์ฒดํฌ +# def visit(x, y, in_visited): +# tmp_visited = [visi[:] for visi in in_visited] +# for i in range(1, n-x): +# tmp_visited[x+i][y] = True # ์•„๋ž˜ ๋ฐฉํ–ฅ ์ฒดํฌ +# if 0 <= y-i < n: +# tmp_visited[x+i][y-i] = True # ์™ผ์ชฝ ์•„๋ž˜ ๋Œ€๊ฐ์„  ์ฒดํฌ +# if 0 <= y+i < n: +# tmp_visited[x+i][y+i] = True # ์˜ค๋ฅธ์ชฝ ์•„๋ž˜ ๋Œ€๊ฐ์„  ์ฒดํฌ +# return tmp_visited + + +# def recursion(q, _visited): # q๋ฒˆ์งธ ์ค„์— ํ€ธ์„ ๋‘˜ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋“ค์„ ํ™•์ธํ•˜๋Š” ์žฌ๊ท€ํ•จ์ˆ˜ +# global result +# # ํ•œ ์ค„์— ํ€ธ์ด ํ•˜๋‚˜์”ฉ ๋“ค์–ด๊ฐ€์•ผ ํ•จ +# # ํ•œ ์ค„ ์ „์ฒด๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ ์•„์˜ˆ n๊ฐœ์˜ ํ€ธ์„ ๋ชจ๋‘ ๋†“์„ ์ˆ˜ ์—†์œผ๋ฏ€๋กœ ์žฌ๊ท€ ์ข…๋ฃŒ +# for idx in range(q, n): +# if sum(_visited[idx]) == n: +# return 0 +# # ๋งˆ์ง€๋ง‰ ์ค„์— ๋„๋‹ฌํ•œ ๊ฒฝ์šฐ ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ์„ธ๊ณ  ์žฌ๊ท€ ์ข…๋ฃŒ +# if q == (n-1): +# result += n - sum(_visited[q]) +# return 0 + +# for i in range(n): +# if not _visited[q][i]: # ํ€ธ์„ ๋‘˜ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ +# tmp = visit(q, i, _visited) # ํ€ธ์„ ๋’€์„ ๋•Œ ๋ถˆ๊ฐ€๋Šฅํ•œ ์นธ๋“ค ์ฒดํฌ +# recursion(q+1, tmp) # ๊ทธ ๋‹ค์Œ ์ค„์— ๋Œ€ํ•ด ์žฌ๊ท€ ํ˜ธ์ถœ +# # ์žฌ๊ท€ํ˜ธ์ถœ ์ข…๋ฃŒ ํ›„ ํ€ธ์„ ๋‘˜ ์ˆ˜ ์žˆ๋Š” ๋‹ค๋ฅธ ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ์ฒดํฌ + + +# visited = [[False for _ in range(n)] for _ in range(n)] +# recursion(0, visited) # 0๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ ํƒ์ƒ‰ ์‹œ์ž‘ +# print(result) + + + +#๋ฐ•์ฐฌ์šฐ๋‹˜์˜ ์ฝ”๋“œ + +global cnt +cnt = 0 + +def n_queen (col, i) : + n = len(col) - 1 + if (judge(col, i)) : + if(i==n) : + print(col[1: n+1]) + else : + for j in range(1, n+1) : + col[i+1] = j + n_queen(col, i+1, cnt) + + print(cnt) + +def judge(col, i) : + k = 1 + flag = True + while (k < i and flag) : + if (col[i] == col[k] or abs(col[i] - col[k]) == (i - k)) : + flag = False + k += 1 + return flag + +n = 8 +a = [0] * (n+1) +n_queen(a, 0, 0) \ No newline at end of file
Python
์ €๋„ ๋‚จ์˜ ๊ฑฐ ์ฐธ๊ณ ํ•œ๊ฑฐ๋ผ ๋ถ€๋„๋Ÿฝ๋„ค์š” ใ…  ์ด์ฐจ์› ๋ฐฐ์—ด๋กœ ํ•˜๋‹ค๊ฐ€ 1์ฐจ์›๋ฐฐ์—ด๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค๋Š” ๋ฐœ์ƒ์ด ์–ด๋ ค์› ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,23 @@ +# https://www.acmicpc.net/problem/1181 +# https://blockdmask.tistory.com/543 +# set์„ ์ด์šฉํ•˜๋ฉด ์ค‘๋ณต์ด ์ œ๊ฑฐ๋จ +# https://always-challenger-lab.tistory.com/22 +# ๋žŒ๋‹ค ์ด์šฉํ•ด์„œ ๋‹ค์ค‘์กฐ๊ฑด ์ •๋ ฌ +import sys + +n = int(sys.stdin.readline()) +s = [] +m = [] +for i in range(n): + s.append(str(sys.stdin.readline().strip())) + + +set_s = list(set(s)) +for j in set_s: + m.append([j,len(j)]) + +print(m) +m.sort(key=lambda x:(x[1],x[0])) + +for i in m: + print(i[0]) \ No newline at end of file
Python
๋žŒ๋‹ค ์‚ฌ์šฉ์ด ์‹ ๋ฐ•ํ—ค๋„ค์š” ใ…‡.ใ…‡ ์ฐธ๊ณ ๊ฐ€ ๋์Šต๋‹ˆ๋‹ค.
@@ -1,152 +1,44 @@ package com.example.project.compile.service; +import com.example.project.compile.domain.CompileLanguage; import com.example.project.error.dto.ErrorMessage; -import org.springframework.beans.factory.annotation.Value; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.io.IOException; -import java.nio.file.*; -import java.util.UUID; +import java.nio.file.Files; +import java.nio.file.Path; +@Slf4j @Service +@RequiredArgsConstructor public class CompileService { - private final String code_dir; - public CompileService(@Value("${compile.url}") String codeDir) { - this.code_dir = codeDir; - } + private final FileService fileService; + private final CommandExecutorService commandExecutorService; - public String compileAndRun(String language, String code) throws IOException, InterruptedException { + public String compileAndRun(String language, String code, String codeDir) throws IOException { + CompileLanguage compileLanguage = CompileLanguage.JAVA.getByLanguageName(language); + Path filePath = null; try { - Path codePath = Paths.get(code_dir); - if (!Files.exists(codePath)) { - Files.createDirectories(codePath); + filePath = fileService.createCodeFile(code, compileLanguage, codeDir); + return executeCode(filePath); + } finally { + if (filePath != null) { + Files.deleteIfExists(filePath); } - - String filename = generateFileName(language); - Path filePath = codePath.resolve(filename); - - Files.write(filePath, code.getBytes()); - - return executeCode(language, filePath, codePath); - } catch (FileAlreadyExistsException e) { - throw new IOException(ErrorMessage.CODE_DIRECTORY_CREATION_FAILED.getMessage(), e); - } catch (IOException e) { - throw new IOException(ErrorMessage.CODE_WRITE_FAILED.getMessage(), e); } } - private String executeCode(String language, Path filePath, Path codePath) throws IOException, InterruptedException { + private String executeCode(Path filePath) throws IOException { + String result; try { - //TODO Enum ์‚ฌ์šฉํ•˜๊ธฐ - return switch (language.toLowerCase()) { - case "c" -> compileAndRun(filePath, "gcc", codePath.resolve("output").toString(), ""); - case "java" -> compileJava(filePath); - case "python" -> compilePython(filePath); - default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage()); - }; - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage(), e); + String command = filePath.getParent().resolve("output").toString(); + result = commandExecutorService.runCommand(command); } catch (IOException | InterruptedException e) { throw new IOException(ErrorMessage.GENERAL_COMPILE_ERROR.getMessage(), e); } - } - - private String compileAndRun(Path filePath, String compiler, String outputFileName, String additionalArgs) throws IOException, InterruptedException { - String command = String.format("%s %s -o %s %s", compiler, filePath, outputFileName, additionalArgs); - Process compileProcess = Runtime.getRuntime().exec(command); - compileProcess.waitFor(); - - if (compileProcess.exitValue() == 0) { - return runCompiledProgram(outputFileName); - } else { - String errorOutput = new String(compileProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String runCompiledProgram(String outputFileName) throws IOException, InterruptedException { - Process runProcess = Runtime.getRuntime().exec(outputFileName); - runProcess.waitFor(); - - if (runProcess.exitValue() == 0) { - return new String(runProcess.getInputStream().readAllBytes()); - } else { - String errorOutput = new String(runProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String compileJava(Path filePath) throws IOException, InterruptedException { - String className = extractClassName(filePath); - Path correctFilePath = filePath.getParent().resolve(className + ".java"); - - try { - Files.move(filePath, correctFilePath, StandardCopyOption.REPLACE_EXISTING); - } catch (FileAlreadyExistsException e) { - throw new IOException(ErrorMessage.JAVA_FILE_RENAMING_FAILED.getMessage(), e); - } - - String command = String.format("javac %s", correctFilePath); - Process compileProcess = Runtime.getRuntime().exec(command); - compileProcess.waitFor(); - - if (compileProcess.exitValue() == 0) { - return runJavaProgram(correctFilePath); - } else { - String errorOutput = new String(compileProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String extractClassName(Path filePath) throws IOException { - try { - String content = Files.readString(filePath); - return content.split("public class ")[1].split("\\s")[0].trim(); - } catch (Exception e) { - throw new IOException(ErrorMessage.JAVA_CLASS_EXTRACTION_FAILED.getMessage(), e); - } - } - - private String runJavaProgram(Path filePath) throws IOException, InterruptedException { - String className = filePath.getFileName().toString().replace(".java", ""); - String runCommand = String.format("java -cp %s %s", filePath.getParent(), className); - - Process runProcess = Runtime.getRuntime().exec(runCommand); - runProcess.waitFor(); - - if (runProcess.exitValue() == 0) { - return new String(runProcess.getInputStream().readAllBytes()); - } else { - String errorOutput = new String(runProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String compilePython(Path filePath) throws IOException, InterruptedException { - String command = String.format("python %s", filePath); - Process process = Runtime.getRuntime().exec(command); - process.waitFor(); - - if (process.exitValue() == 0) { - return new String(process.getInputStream().readAllBytes()); - } else { - String errorOutput = new String(process.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String generateFileName(String language) { - return UUID.randomUUID() + getExtension(language); - } - - private String getExtension(String language) { - //TODO ENUM - return switch (language.toLowerCase()) { - case "c" -> ".c"; - case "java" -> ".java"; - case "python" -> ".py"; - default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage()); - }; + return result; } } \ No newline at end of file
Java
enum์„ ์‚ฌ์šฉํ•ฉ์‹œ๋‹ค
@@ -1,152 +1,44 @@ package com.example.project.compile.service; +import com.example.project.compile.domain.CompileLanguage; import com.example.project.error.dto.ErrorMessage; -import org.springframework.beans.factory.annotation.Value; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.io.IOException; -import java.nio.file.*; -import java.util.UUID; +import java.nio.file.Files; +import java.nio.file.Path; +@Slf4j @Service +@RequiredArgsConstructor public class CompileService { - private final String code_dir; - public CompileService(@Value("${compile.url}") String codeDir) { - this.code_dir = codeDir; - } + private final FileService fileService; + private final CommandExecutorService commandExecutorService; - public String compileAndRun(String language, String code) throws IOException, InterruptedException { + public String compileAndRun(String language, String code, String codeDir) throws IOException { + CompileLanguage compileLanguage = CompileLanguage.JAVA.getByLanguageName(language); + Path filePath = null; try { - Path codePath = Paths.get(code_dir); - if (!Files.exists(codePath)) { - Files.createDirectories(codePath); + filePath = fileService.createCodeFile(code, compileLanguage, codeDir); + return executeCode(filePath); + } finally { + if (filePath != null) { + Files.deleteIfExists(filePath); } - - String filename = generateFileName(language); - Path filePath = codePath.resolve(filename); - - Files.write(filePath, code.getBytes()); - - return executeCode(language, filePath, codePath); - } catch (FileAlreadyExistsException e) { - throw new IOException(ErrorMessage.CODE_DIRECTORY_CREATION_FAILED.getMessage(), e); - } catch (IOException e) { - throw new IOException(ErrorMessage.CODE_WRITE_FAILED.getMessage(), e); } } - private String executeCode(String language, Path filePath, Path codePath) throws IOException, InterruptedException { + private String executeCode(Path filePath) throws IOException { + String result; try { - //TODO Enum ์‚ฌ์šฉํ•˜๊ธฐ - return switch (language.toLowerCase()) { - case "c" -> compileAndRun(filePath, "gcc", codePath.resolve("output").toString(), ""); - case "java" -> compileJava(filePath); - case "python" -> compilePython(filePath); - default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage()); - }; - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage(), e); + String command = filePath.getParent().resolve("output").toString(); + result = commandExecutorService.runCommand(command); } catch (IOException | InterruptedException e) { throw new IOException(ErrorMessage.GENERAL_COMPILE_ERROR.getMessage(), e); } - } - - private String compileAndRun(Path filePath, String compiler, String outputFileName, String additionalArgs) throws IOException, InterruptedException { - String command = String.format("%s %s -o %s %s", compiler, filePath, outputFileName, additionalArgs); - Process compileProcess = Runtime.getRuntime().exec(command); - compileProcess.waitFor(); - - if (compileProcess.exitValue() == 0) { - return runCompiledProgram(outputFileName); - } else { - String errorOutput = new String(compileProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String runCompiledProgram(String outputFileName) throws IOException, InterruptedException { - Process runProcess = Runtime.getRuntime().exec(outputFileName); - runProcess.waitFor(); - - if (runProcess.exitValue() == 0) { - return new String(runProcess.getInputStream().readAllBytes()); - } else { - String errorOutput = new String(runProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String compileJava(Path filePath) throws IOException, InterruptedException { - String className = extractClassName(filePath); - Path correctFilePath = filePath.getParent().resolve(className + ".java"); - - try { - Files.move(filePath, correctFilePath, StandardCopyOption.REPLACE_EXISTING); - } catch (FileAlreadyExistsException e) { - throw new IOException(ErrorMessage.JAVA_FILE_RENAMING_FAILED.getMessage(), e); - } - - String command = String.format("javac %s", correctFilePath); - Process compileProcess = Runtime.getRuntime().exec(command); - compileProcess.waitFor(); - - if (compileProcess.exitValue() == 0) { - return runJavaProgram(correctFilePath); - } else { - String errorOutput = new String(compileProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String extractClassName(Path filePath) throws IOException { - try { - String content = Files.readString(filePath); - return content.split("public class ")[1].split("\\s")[0].trim(); - } catch (Exception e) { - throw new IOException(ErrorMessage.JAVA_CLASS_EXTRACTION_FAILED.getMessage(), e); - } - } - - private String runJavaProgram(Path filePath) throws IOException, InterruptedException { - String className = filePath.getFileName().toString().replace(".java", ""); - String runCommand = String.format("java -cp %s %s", filePath.getParent(), className); - - Process runProcess = Runtime.getRuntime().exec(runCommand); - runProcess.waitFor(); - - if (runProcess.exitValue() == 0) { - return new String(runProcess.getInputStream().readAllBytes()); - } else { - String errorOutput = new String(runProcess.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String compilePython(Path filePath) throws IOException, InterruptedException { - String command = String.format("python %s", filePath); - Process process = Runtime.getRuntime().exec(command); - process.waitFor(); - - if (process.exitValue() == 0) { - return new String(process.getInputStream().readAllBytes()); - } else { - String errorOutput = new String(process.getErrorStream().readAllBytes()); - throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput); - } - } - - private String generateFileName(String language) { - return UUID.randomUUID() + getExtension(language); - } - - private String getExtension(String language) { - //TODO ENUM - return switch (language.toLowerCase()) { - case "c" -> ".c"; - case "java" -> ".java"; - case "python" -> ".py"; - default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage()); - }; + return result; } } \ No newline at end of file
Java
ํด๋ž˜์Šค๊ฐ€ ๋„ˆ๋ฌด ํฝ๋‹ˆ๋‹ค. ์—ญํ• ์„ ๋‚˜๋ˆ ์ฃผ์„ธ์š”
@@ -1,36 +1,40 @@ package com.example.project.compile.controller.rest; +import com.example.project.auth.service.AuthTokenService; import com.example.project.common.dto.ResponseDto; import com.example.project.common.dto.ResponseMessage; -import com.example.project.solution.dto.request.user.SolutionCompileRequest; +import com.example.project.common.util.HeaderUtil; +import com.example.project.compile.dto.CompileRequest; import com.example.project.compile.service.CompileService; +import com.example.project.error.dto.ErrorMessage; +import com.example.project.error.dto.ErrorResponseDto; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.io.IOException; +@Slf4j @RestController @RequiredArgsConstructor @RequestMapping("/api/compile") public class CompileApiController { + private final CompileService compileService; + private final AuthTokenService authTokenService; @PostMapping - @PreAuthorize("hasAnyRole('USER', 'ADMIN')") - public ResponseEntity<?> compileCode(@RequestBody SolutionCompileRequest request) { - try { - String result = compileService.compileAndRun(request.getLanguage(), request.getCode()); + public ResponseEntity<?> compileCode(@RequestBody CompileRequest request, HttpServletRequest httpServletRequest, @Value("${compile.url}") String codeDir) throws IOException { + if (authTokenService.isValidateToken(HeaderUtil.resolveToken(httpServletRequest))) { + String result = compileService.compileAndRun( + request.getLanguage(), + request.getCode(), + codeDir + ); return ResponseDto.toResponseEntity(ResponseMessage.COMPILE_SUCCESS, result); - } catch (IllegalArgumentException e) { - return ResponseDto.toResponseEntity(ResponseMessage.INVALID_LANGUAGE, e.getMessage()); - } catch (IOException e) { - return ResponseDto.toResponseEntity(ResponseMessage.IO_ERROR, e.getMessage()); - } catch (InterruptedException e) { - return ResponseDto.toResponseEntity(ResponseMessage.EXECUTION_INTERRUPTED, e.getMessage()); - } catch (Exception e) { - return ResponseDto.toResponseEntity(ResponseMessage.GENERAL_COMPILE_ERROR, e.getMessage()); - } + } else return ErrorResponseDto.of(ErrorMessage.NOT_FOUND_CLIENT_ID_HEADER); } } \ No newline at end of file
Java
HttpServletRequest๋งŒ ๋ฐ›์•„์˜ค๋ฉด ํ† ํฐ ๊ฐ’์„ ๋”ฐ๋กœ ๋ฐ›์•„์˜ค์ง€ ์•Š์•„๋„ ๋ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,37 @@ +package com.example.project.compile.service; + +import com.example.project.compile.domain.CompileLanguage; +import com.example.project.error.dto.ErrorMessage; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.UUID; + +@Service +public class FileService { + + public Path createCodeFile(String code, CompileLanguage compileLanguage, String codeDir) throws IOException { + try { + Path codePath = Paths.get(codeDir); + if (!Files.exists(codePath)) { + Files.createDirectories(codePath); + } + + //UUID๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ ๋Š” ๊ณ ์œ ํ•œ ํŒŒ์ผ ์ด๋ฆ„์„ ์ƒ์„ฑํ•˜์—ฌ ํŒŒ์ผ์˜ ์ถฉ๋Œ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•จ์ž…๋‹ˆ๋‹ค. + String filename = "Main_" + UUID.randomUUID() + compileLanguage.getExtension(); + + Path filePath = codePath.resolve(filename); + Files.writeString(filePath, code); + return filePath; + + } catch (InvalidPathException e) { + throw new IOException(ErrorMessage.INVALID_PATH_EXCEPTION.getMessage(), e); + } catch (SecurityException e) { + throw new IOException(ErrorMessage.ACCESS_PERMISSION_EXCEPTION.getMessage(), e); + } + } +} \ No newline at end of file
Java
yml ์— ์„ค์ •ํ•œ ๊ฐ’์„ ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”. ๊ทธ๋ฆฌ๊ณ  static์„ ์‚ฌ์šฉํ•  ํ•„์š”๋Š” ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค.
@@ -1,36 +1,40 @@ package com.example.project.compile.controller.rest; +import com.example.project.auth.service.AuthTokenService; import com.example.project.common.dto.ResponseDto; import com.example.project.common.dto.ResponseMessage; -import com.example.project.solution.dto.request.user.SolutionCompileRequest; +import com.example.project.common.util.HeaderUtil; +import com.example.project.compile.dto.CompileRequest; import com.example.project.compile.service.CompileService; +import com.example.project.error.dto.ErrorMessage; +import com.example.project.error.dto.ErrorResponseDto; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.io.IOException; +@Slf4j @RestController @RequiredArgsConstructor @RequestMapping("/api/compile") public class CompileApiController { + private final CompileService compileService; + private final AuthTokenService authTokenService; @PostMapping - @PreAuthorize("hasAnyRole('USER', 'ADMIN')") - public ResponseEntity<?> compileCode(@RequestBody SolutionCompileRequest request) { - try { - String result = compileService.compileAndRun(request.getLanguage(), request.getCode()); + public ResponseEntity<?> compileCode(@RequestBody CompileRequest request, HttpServletRequest httpServletRequest, @Value("${compile.url}") String codeDir) throws IOException { + if (authTokenService.isValidateToken(HeaderUtil.resolveToken(httpServletRequest))) { + String result = compileService.compileAndRun( + request.getLanguage(), + request.getCode(), + codeDir + ); return ResponseDto.toResponseEntity(ResponseMessage.COMPILE_SUCCESS, result); - } catch (IllegalArgumentException e) { - return ResponseDto.toResponseEntity(ResponseMessage.INVALID_LANGUAGE, e.getMessage()); - } catch (IOException e) { - return ResponseDto.toResponseEntity(ResponseMessage.IO_ERROR, e.getMessage()); - } catch (InterruptedException e) { - return ResponseDto.toResponseEntity(ResponseMessage.EXECUTION_INTERRUPTED, e.getMessage()); - } catch (Exception e) { - return ResponseDto.toResponseEntity(ResponseMessage.GENERAL_COMPILE_ERROR, e.getMessage()); - } + } else return ErrorResponseDto.of(ErrorMessage.NOT_FOUND_CLIENT_ID_HEADER); } } \ No newline at end of file
Java
์ปดํŒŒ์ผํ•˜๋Š” ์„œ๋ฒ„์—์„œ๋„ JWT ํ† ํฐ์„ ๊ฐ€์ง€๊ณ  ์œ ํšจํ•œ ์ ‘๊ทผ์ธ์ง€ ์•„๋‹Œ์ง€ ํŒ๋‹จํ•ด์„œ ์ปดํŒŒ์ผํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ฃผ์„ธ์š”
@@ -0,0 +1,37 @@ +package com.example.project.compile.service; + +import com.example.project.compile.domain.CompileLanguage; +import com.example.project.error.dto.ErrorMessage; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.UUID; + +@Service +public class FileService { + + public Path createCodeFile(String code, CompileLanguage compileLanguage, String codeDir) throws IOException { + try { + Path codePath = Paths.get(codeDir); + if (!Files.exists(codePath)) { + Files.createDirectories(codePath); + } + + //UUID๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ ๋Š” ๊ณ ์œ ํ•œ ํŒŒ์ผ ์ด๋ฆ„์„ ์ƒ์„ฑํ•˜์—ฌ ํŒŒ์ผ์˜ ์ถฉ๋Œ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•จ์ž…๋‹ˆ๋‹ค. + String filename = "Main_" + UUID.randomUUID() + compileLanguage.getExtension(); + + Path filePath = codePath.resolve(filename); + Files.writeString(filePath, code); + return filePath; + + } catch (InvalidPathException e) { + throw new IOException(ErrorMessage.INVALID_PATH_EXCEPTION.getMessage(), e); + } catch (SecurityException e) { + throw new IOException(ErrorMessage.ACCESS_PERMISSION_EXCEPTION.getMessage(), e); + } + } +} \ No newline at end of file
Java
๋ณ€์ˆ˜๋ช…์€ ์นด๋ฉœ์ผ€์ด์Šค๋ฅผ ์ง€์ผœ์„œ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”
@@ -0,0 +1,9 @@ +package com.codesquad.baseballgame.domain.game.controller; + +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class GameController { + + +}
Java
์Œ. ์ด๋Ÿฐ ์ปจํŠธ๋กค๋Ÿฌ๋Š” ์“ฐ์ง€ ์•Š๋Š”๋‹ค๋ฉด ๊ทธ๋•Œ๊ทธ๋•Œ ์ง€์›Œ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,24 @@ +package com.codesquad.baseballgame.domain.game.controller; + +import com.codesquad.baseballgame.domain.game.service.MatchService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +public class MatchController { + + private final MatchService matchService; + + @PostMapping("games/{id}") + public ResponseEntity<Boolean> matching(@PathVariable int id) { + if (matchService.matchStatus(id)) { + return new ResponseEntity<>(true, HttpStatus.OK); + } + return new ResponseEntity<>(false, HttpStatus.OK); + } +}
Java
์„ค๊ณ„ํ•˜๊ธฐ ๋‚˜๋ฆ„์ด๊ธด ํ•˜์ง€๋งŒ, `@PathVariable` ๋งŒ์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›๋Š” ์—”๋“œํฌ์ธํŠธ์—์„œ `POST` ๋ฅผ ์“ฐ๋Š”๊ฑด ๋‹ค์†Œ ์–ด์ƒ‰ํ•ด๋ณด์ด๊ธด ํ•˜๋„ค์š”. ๋ญ”๊ฐ€๊ฐ€ ๋ˆ„๋ฝ๋œ ๊ฑด ์•„๋‹Œ๊ฐ€์š”. ๋ฆฌํ„ด ๋ฐ”๋””์— `true` `false` ๋งŒ์„ ์‹ฃ๋Š” ๊ฒƒ๋„ ์ข€ ์–ด์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,7 @@ +package com.codesquad.baseballgame.domain.game.dao; + +import org.springframework.stereotype.Repository; + +@Repository +public class GameDao { +}
Java
์Œ ์—ฌ๊ธฐ๋„ ๋น„์–ด์žˆ๊ตฐ์š”?
@@ -0,0 +1,14 @@ +package com.codesquad.baseballgame.domain.game.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.ToString; + +@Getter @ToString +@RequiredArgsConstructor +public class BallCountDto { + + private int strike; + private int ball; + private int out; +}
Java
์• ๋…ธํ…Œ์ด์…˜์€ ํ•œ ์ค„์— ํ•˜๋‚˜๋ฅผ ์“ฐ๋Š” ๊ฒƒ์„ ์›์น™์œผ๋กœ ํ•ด ์ฃผ์„ธ์š”. ```suggestion @Getter @ToString
@@ -0,0 +1,14 @@ +package com.codesquad.baseballgame.domain.game.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.ToString; + +@Getter @ToString +@RequiredArgsConstructor +public class BallCountDto { + + private int strike; + private int ball; + private int out; +}
Java
์ƒ์„ฑ์ž๊ฐ€ ์›ํ•˜๋Š” ๋Œ€๋กœ ์ƒ์„ฑ๋˜์—ˆ๋‚˜์š”? ์ œ๊ฐ€ ์•Œ๊ธฐ๋กœ ์ด ์• ๋…ธํ…Œ์ด์…˜์€ `final` ํ•„๋“œ์— ๋Œ€ํ•ด์„œ๋งŒ ์ƒ์„ฑ์ž๋ฅผ ๋งŒ๋“œ๋Š”๋ฐ์š”. ์•„๋ž˜ ์–ด๋–ค ํ•„๋“œ๋„ `final` ์˜ˆ์•ฝ์–ด๋ฅผ ๊ฐ–์ง€ ์•Š๋„ค์š”.
@@ -0,0 +1,10 @@ +package com.codesquad.baseballgame.domain.game.service; + +import org.springframework.stereotype.Service; + +@Service +public class GameService { + + + +}
Java
์™œ ์ด๋ ‡๊ฒŒ ๋น„์–ด์žˆ๋Š” ํด๋ž˜์Šค๋“ค์ด ๋งŽ์€๊ฑฐ์ฃ ...
@@ -0,0 +1,23 @@ +package com.codesquad.baseballgame.domain.game.service; + +import com.codesquad.baseballgame.domain.team.dao.TeamDao; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MatchService { + + private final TeamDao teamDao; + + @Transactional(isolation = Isolation.SERIALIZABLE) + public Boolean matchStatus(int id) { + return countMatchUser(id) == 2; + } + + public Integer countMatchUser(int id) { + return teamDao.countMatchUser(id); + } +}
Java
`SERIALIZABLE` ์ •๋ง ๊ดœ์ฐฎ์„๊นŒ์š”? ์ •ํ™•ํžˆ ์ดํ•ดํ•˜๊ณ  ์‚ฌ์šฉํ•˜์‹  ๊ฑด๊ฐ€์š”. ๋Œ€๋ถ€๋ถ„์˜ ๊ฒฝ์šฐ `SERIALIZABLE` ๊นŒ์ง€ ๊ณ ๋ฆฝ์‹œ์ผœ์•ผ ํ•  ํŠธ๋žœ์žญ์…˜์€ ์—†์Šต๋‹ˆ๋‹ค. ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋ ˆ์ด์–ด์—์„œ ์ด๋Ÿฐ ์ˆ˜์ค€์˜ ๊ณ ๋ฆฝ์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ, ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋กœ์ง์„ ๋‹ค์‹œ ๊ฒ€ํ† ํ•ด์„œ ์ •๋ง ์ด์ •๋„์˜ ํŠธ๋žœ์žญ์…˜์ด ํ•„์š”ํ•œ์ง€ ์‚ดํŽด๋ณด๊ณ , ์ •๋ง ๊ณ ๋ฆฝ ์ˆ˜์ค€ ์กฐ์ •์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ์—๋„, ์‚ฌ์‹ค์€ ๊ณ ๋ฆฝ ์ˆ˜์ค€ ์กฐ์ •์ด ์•„๋‹ˆ๋ผ propagation ์ „๋žต ์ˆ˜์ •์œผ๋กœ ๋Œ€์‘ํ•  ์ˆ˜ ์žˆ์ง€๋Š” ์•Š์€์ง€ ๋‹ค์‹œ ํ•œ ๋ฒˆ ์ƒ๊ฐํ•ด๋ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์•„๋งˆ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ๋Š” ์ฟผ๋ฆฌ๊ฐ€ ์žˆ๋‹ค๋ณด๋‹ˆ ์ฟผ๋ฆฌ๊ฐ€ ๋„๋Š” ๋™์•ˆ ์ƒˆ๋กœ์šด ์ปค๋ฐ‹์ด ์ผ์–ด๋‚˜์„œ ๊ฒฐ๊ณผ๊ฐ€ ๋’ค๋ฐ”๋€Œ๋Š” ์ผ์„ ์šฐ๋ คํ–ˆ์„์ง€๋„ ๋ชจ๋ฅด๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ ๊ฒฝ์šฐ๋ผ๋ฉด `READ COMMITTED` ๋กœ ์ถฉ๋ถ„ํ•˜์ง€ ์•Š๋‚˜์š”. ์Œ.....
@@ -0,0 +1,23 @@ +package com.codesquad.baseballgame.domain.game.service; + +import com.codesquad.baseballgame.domain.team.dao.TeamDao; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MatchService { + + private final TeamDao teamDao; + + @Transactional(isolation = Isolation.SERIALIZABLE) + public Boolean matchStatus(int id) { + return countMatchUser(id) == 2; + } + + public Integer countMatchUser(int id) { + return teamDao.countMatchUser(id); + } +}
Java
`@Transactional` ์ด ์„ ์–ธ๋œ ๋ฉ”์†Œ๋“œ์—์„œ ์ด๋ ‡๊ฒŒ ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด, ํŠธ๋žœ์žญ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. https://mommoo.tistory.com/92
@@ -0,0 +1,20 @@ +package com.codesquad.baseballgame.domain.hitter.mapper; + +import com.codesquad.baseballgame.domain.hitter.dto.HitterListDto; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class HitterListMapper implements RowMapper<HitterListDto> { + + @Override + public HitterListDto mapRow(ResultSet rs, int rowNum) throws SQLException { + return HitterListDto.builder() + .teamName(rs.getString("name")) + .totalsBatterBox(rs.getInt("total_sum")) + .totalsHit(rs.getInt("total_hit")) + .totalsOut(rs.getInt("total_out")) + .build(); + } +}
Java
`RowMapper` ์—์„œ ๋ฐ”๋กœ DTO๋กœ ๋งคํ•‘ํ•˜๋„ค์š”. ๋ชจ๋ธ ํด๋ž˜์Šค๊ฐ€ ํ•˜๋‚˜ ์žˆ๋Š”๊ฒŒ ์ข‹๊ธด ํ•œ๋ฐ... ๋ชจ๋ธ ํด๋ž˜์Šค์˜ ํ•„์š”์„ฑ์ด ์—†์—ˆ๋‚˜๋ณด๋„ค์š”.
@@ -0,0 +1,15 @@ +package com.codesquad.baseballgame.domain.scoreboard.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ScoreBoardController { + + @GetMapping("games/{id}/scoreboard") + public void showScoreBoard(@PathVariable int id) { + + + } +}
Java
์Œ......
@@ -0,0 +1,23 @@ +package com.codesquad.baseballgame.domain.scoreboard.dao; + +import com.codesquad.baseballgame.domain.scoreboard.dto.ScoreBoardInningDto; +import com.codesquad.baseballgame.domain.team.mapper.TeamDtoMapper; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.stereotype.Repository; + +import javax.sql.DataSource; + +@Repository +public class ScoreBoardDao { + + private final NamedParameterJdbcTemplate namedJdbcTemplate; + private final TeamDtoMapper teamDtoMapper = new TeamDtoMapper(); + + public ScoreBoardDao(DataSource dataSource) { + this.namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + } + +// public ScoreBoardInningDto findInningById(int id) { +// String inningSql = "" +// } +}
Java
์ฃผ์„์€ ์ง€์›Œ์ฃผ์„ธ์š”.
@@ -0,0 +1,9 @@ +package com.codesquad.baseballgame.domain.game.controller; + +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class GameController { + + +}
Java
๋„ค ๊ผญ ์ง€์šฐ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค ์ ˆ๋Œ€ ํ•ด์„  ์•ˆ๋˜๋Š” ์ง“์„ ํ•ด๋ฒ„๋ ธ๊ตฐ์š”. ๊ผญ ๋ช…์‹ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,24 @@ +package com.codesquad.baseballgame.domain.game.controller; + +import com.codesquad.baseballgame.domain.game.service.MatchService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +public class MatchController { + + private final MatchService matchService; + + @PostMapping("games/{id}") + public ResponseEntity<Boolean> matching(@PathVariable int id) { + if (matchService.matchStatus(id)) { + return new ResponseEntity<>(true, HttpStatus.OK); + } + return new ResponseEntity<>(false, HttpStatus.OK); + } +}
Java
์“ฐ๋ฉด์„œ ์•„๋ฟ”์‹ธ.. ํ•˜๊ณ  ๋А๋‚Œ์€ ์™”์—ˆ๋Š”๋ฐ.. ๋งˆ์ง€๋ง‰์— ๋งŒ๋“œ๋А๋ผ ๊ธฐ๋ณธ ๋ฒ•์น™์„ ์žŠ๊ณ  ๋ง‰ ๋งŒ๋“ ๊ฒŒ ์›์ธ์ด์—ˆ์Šต๋‹ˆ๋‹ค. ๊ธ‰ํ•˜๋”๋ผ๋„ ์ง€ํ‚ฌ๊ฑด ์ง€ํ‚ค๋ฉด์„œ ๋งŒ๋“ค์–ด์•ผํ•˜๋Š”๋ฐ ์ œ๊ฐ€ ๋„ˆ๋ฌด ์„œ๋‘˜๋ €๋„ค์š”. ์ตœ์†Œํ•œ์˜ Json์€ ๋งŒ๋“ค์—ˆ์–ด์•ผํ–ˆ๋Š”๋ฐ ๋‹ค์Œ์—๋Š” ์ง€ํ‚ค๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,7 @@ +package com.codesquad.baseballgame.domain.game.dao; + +import org.springframework.stereotype.Repository; + +@Repository +public class GameDao { +}
Java
๋„ค... ๋งž์•„์š” ์ง€์› ์–ด์•ผํ–ˆ์–ด์š”.
@@ -0,0 +1,14 @@ +package com.codesquad.baseballgame.domain.game.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.ToString; + +@Getter @ToString +@RequiredArgsConstructor +public class BallCountDto { + + private int strike; + private int ball; + private int out; +}
Java
์—ฌ๋Ÿฌ์ƒ๊ฐ ํ•˜๋ฉด์„œ ์ฝ”๋”ฉํ•˜๋‹ค๊ฐ€ ์•„๋ฌด๊ฑฐ๋‚˜ ๋‹ค ๋„ฃ๋Š”๋ฐ”๋žŒ์— ์ƒ๊ธด ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. ๊ธฐ๋Šฅ ํ•˜๋‚˜๋งŒ๋“ค ๋•Œ ๊ทธ๋•Œ ์ง‘์ค‘ํ–ˆ์–ด์•ผ ํ–ˆ๋Š”๋ฐ ์ด๊ฒƒ ์ €๊ฒƒํ•˜๋‹ค๊ฐ€ ์ด๋„์ €๋„ ์•„๋‹ˆ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ œ๊ฐ€ ์ด๊ฑธ ๋„ฃ์—ˆ๋‹ค๋Š”๊ฒƒ๋„ ์ง€๊ธˆ ์•Œ์•˜๋„ค์š”. Dto ์—์„  ๋„ฃ์„ ์ƒ๊ฐ ์—†์—ˆ๋Š”๋ฐ.... ์ด๋ฒˆ ๊ธฐํšŒ๋กœ ์ •์‹  ๋˜‘๋ฐ”๋กœ ์ฐจ๋ ค์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,23 @@ +package com.codesquad.baseballgame.domain.game.service; + +import com.codesquad.baseballgame.domain.team.dao.TeamDao; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MatchService { + + private final TeamDao teamDao; + + @Transactional(isolation = Isolation.SERIALIZABLE) + public Boolean matchStatus(int id) { + return countMatchUser(id) == 2; + } + + public Integer countMatchUser(int id) { + return teamDao.countMatchUser(id); + } +}
Java
ํŠธ๋žœ์ ์…˜์— ๋Œ€ํ•œ ๋‚ด์šฉ์„ ๋ธ”๋กœ๊ทธ์—์„œ ๊ฐ€๋ณ๊ฒŒ ๋ณด๊ณ  ์ด ๋•Œ ์“ฐ๋Š”๊ฑด๊ฐ€ ํ•˜๊ณ  ์ผ๋Š”๋ฐ ์ข€ ๋” ๊ณต๋ถ€๊ฐ€ ํ•„์š”ํ•˜๋Š”๊ตฐ์š”. Read Committed ์— ๋Œ€ํ•ด์„œ ์กฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,20 @@ +package com.codesquad.baseballgame.domain.hitter.mapper; + +import com.codesquad.baseballgame.domain.hitter.dto.HitterListDto; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class HitterListMapper implements RowMapper<HitterListDto> { + + @Override + public HitterListDto mapRow(ResultSet rs, int rowNum) throws SQLException { + return HitterListDto.builder() + .teamName(rs.getString("name")) + .totalsBatterBox(rs.getInt("total_sum")) + .totalsHit(rs.getInt("total_hit")) + .totalsOut(rs.getInt("total_out")) + .build(); + } +}
Java
๋ชจ๋ธ ํด๋ž˜์Šค์˜ ํ•„์š”์„ฑ์ด ์—†์—ˆ๋‹ค๊ธฐ๋ณด๋‹จ ์„ค๊ณ„๊ฐ€ ์ž˜๋ชป๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๋ชจ๋ธํด๋ž˜์Šค์— ๋งž๊ฒŒ ํ–ˆ๋‹ค๋ฉด ์ง€๊ธˆ๋ณด๋‹ค ๋”์šฑ ๋น ๋ฅด๊ฒŒ ์ฝ”๋”ฉ์ด ๋˜์—ˆ์„ํ…๋ฐ ์•„์‰ฝ์Šต๋‹ˆ๋‹ค. ์„ค๊ณ„๋ฅผ ๊ผญ ์ œ๋Œ€๋กœ ๋งž์ถฐ์•ผ๊ฒ ๋„ค์š”
@@ -0,0 +1,23 @@ +package com.codesquad.baseballgame.domain.scoreboard.dao; + +import com.codesquad.baseballgame.domain.scoreboard.dto.ScoreBoardInningDto; +import com.codesquad.baseballgame.domain.team.mapper.TeamDtoMapper; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.stereotype.Repository; + +import javax.sql.DataSource; + +@Repository +public class ScoreBoardDao { + + private final NamedParameterJdbcTemplate namedJdbcTemplate; + private final TeamDtoMapper teamDtoMapper = new TeamDtoMapper(); + + public ScoreBoardDao(DataSource dataSource) { + this.namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + } + +// public ScoreBoardInningDto findInningById(int id) { +// String inningSql = "" +// } +}
Java
๋„ต
@@ -0,0 +1,15 @@ +package com.codesquad.baseballgame.domain.scoreboard.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ScoreBoardController { + + @GetMapping("games/{id}/scoreboard") + public void showScoreBoard(@PathVariable int id) { + + + } +}
Java
์šฉ์„œํ•ด์ฃผ์‹ญ์‹œ์˜ค...
@@ -0,0 +1,23 @@ +package com.codesquad.baseballgame.domain.game.service; + +import com.codesquad.baseballgame.domain.team.dao.TeamDao; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MatchService { + + private final TeamDao teamDao; + + @Transactional(isolation = Isolation.SERIALIZABLE) + public Boolean matchStatus(int id) { + return countMatchUser(id) == 2; + } + + public Integer countMatchUser(int id) { + return teamDao.countMatchUser(id); + } +}
Java
ํŠธ๋žœ์ ์…˜์— ๋Œ€ํ•ด์„œ ํ™•์‹คํ•˜๊ฒŒ ๊ณต๋ถ€ํ•ด์•ผ๊ฒ ๋„ค์š”. ์–ด์„คํ”ˆ ์‚ฌ์šฉ์€ ์ง€์–‘ํ•ด๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,23 @@ +package com.codesquad.baseballgame.domain.game.service; + +import com.codesquad.baseballgame.domain.team.dao.TeamDao; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MatchService { + + private final TeamDao teamDao; + + @Transactional(isolation = Isolation.SERIALIZABLE) + public Boolean matchStatus(int id) { + return countMatchUser(id) == 2; + } + + public Integer countMatchUser(int id) { + return teamDao.countMatchUser(id); + } +}
Java
์•„ ์˜ค๋Š˜ ์ •ํ™•ํ•˜๊ฒŒ ์ˆ˜์—…์„ ํ•˜๋Š”๊ตฐ์š” ๋ฆฌ๋ทฐ๋ณด์ž๋งˆ์ž ์ˆ˜์—…์„ ํ•˜๋‹ˆ ๊ธฐ์ฉ๋‹ˆ๋‹ค. Repeatable Read๋กœ๋งŒ ์ปค๋ฒ„๊ฐ€ ๊ฐ€๋Šฅํ•˜๋„ค์š”
@@ -0,0 +1,28 @@ +package christmas.util; + +public class DateValidator { + private static final String INVALID_DATE_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + public static void validateInput(String input) { + validateNumeric(input); + int date = Integer.parseInt(input); + validateDate(date); + } + + private static void validateNumeric(String input) { + if (input == null) { + throw new ValidationException(INVALID_DATE_MESSAGE); + } + try { + Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new ValidationException(INVALID_DATE_MESSAGE); + } + } + + private static void validateDate(int date) { + if (date < 1 || date > 31) { + throw new ValidationException(INVALID_DATE_MESSAGE); + } + } +}
Java
31์ผ๋กœ ๋๋‚˜์ง€ ์•Š๋Š” ๋‹ฌ๋„ ์žˆ๊ธฐ๋•Œ๋ฌธ์— 12์›”์— ๋Œ€ํ•œ ์˜์กด์„ฑ์„ ์ฃผ์ž…๋ฐ›์•„์„œ ํ•ด๋‹นํ•˜๋Š” ์›”(ๆœˆ)์— ๋งž์ถฐ ์ตœ๋Œ€ ์ผ์ˆ˜๋ฅผ ๋ณ€๊ฒฝ ํ•˜๋˜์ง€ ํ•ด๋‹น ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ์ƒ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๊ทธ ์™ธ ๋‹ค์–‘ํ•œ ๋ฐฉ์‹์œผ๋กœ ์กฐ๊ฑด์„ ์กฐ์ ˆํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„๊ฑฐ๋ผ ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,103 @@ +package christmas.util; + +import christmas.domain.type.Menu; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class OrderValidator { + private static final String LINE_SEPARATOR = System.lineSeparator(); + + private static final int MIN_AMOUNT = 1; + private static final int MAX_AMOUNT = 20; + private static final String INPUT_PATTERN = "([\\S]+-\\d+)(,\\s*[\\S]+-\\d+)*"; + private static final String INVALID_ORDER_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String BEVERAGE_ONLY_MESSAGE = "์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private static final String INVALID_ORDER_AMOUNT_MESSAGE = "๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— 1๊ฐœ์ด์ƒ, ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + private static final String MENU_NOT_EXIST_MESSAGE = "์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ฉ”๋‰ด์ž…๋‹ˆ๋‹ค."; + private static final String DUPLICATED_MENU_ORDER_MESSAGE = "์ค‘๋ณต๋œ ๋ฉ”๋‰ด ํ•ญ๋ชฉ์ด ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static void validateInput(String input) { + checkInputPattern(input); + checkInputPatternMore(input); + List<String> menuNames = parseMenuName(input); + checkDuplicated(menuNames); + + for (String menuName : menuNames) { + checkMenu(menuName); + } + } + + public static void validateOrder(Map<Menu, Integer> order) { + checkAmount(order); + checkBeverageOnly(order); + } + + private static void checkBeverageOnly(Map<Menu, Integer> order) { + if (order.keySet() + .stream() + .allMatch(menu -> menu.getCategory() == Menu.Category.BEVERAGE)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + BEVERAGE_ONLY_MESSAGE); + } + } + + private static void checkAmount(Map<Menu, Integer> order) { + int totalAmount = order.values() + .stream() + .mapToInt(Integer::intValue).sum(); + + if (totalAmount < MIN_AMOUNT || totalAmount > MAX_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + + for (Integer amount : order.values()) { + if (amount < MIN_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + } + } + + private static void checkMenu(String menuName) { + boolean menuExists = Arrays.stream(Menu.values()).anyMatch(menu -> menu.getName().equals(menuName)); + + if (!menuExists) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + MENU_NOT_EXIST_MESSAGE); + } + } + private static void checkDuplicated(List<String> menuNames) { + Set<String> uniqueMenuNames = new HashSet<>(); + + for (String name : menuNames) { + if (!uniqueMenuNames.add(name)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + DUPLICATED_MENU_ORDER_MESSAGE); + } + } + } + + private static void checkInputPattern(String input) { + if (input == null || !Pattern.matches(INPUT_PATTERN, input)) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + + private static List<String> parseMenuName(String input) { + List<String> menuNames = Arrays.stream(input.split(",")) + .map(order -> order.trim().split("-")[0].trim()) + .collect(Collectors.toList()); + + return menuNames; + } + + private static void checkInputPatternMore(String input) { + String[] items = input.split(","); + + for (String item : items) { + int count = StringUtil.countMatches(item, '-'); + if (count != 1) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + } + +}
Java
์ •๊ทœ์‹์„ ์‚ฌ์šฉํ•  ๋•Œ ๋ฏธ๋ฆฌ ์บ์‹ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค! https://mntdev.tistory.com/69#%F0%9F%91%8D%20%EC%A0%95%EC%A0%81%20%ED%8C%A9%ED%84%B0%EB%A6%AC%EB%A5%BC%20%EC%A0%9C%EA%B3%B5%ED%95%98%EB%8A%94%20%EB%B6%88%EB%B3%80%20%ED%81%B4%EB%9E%98%EC%8A%A4-1 ์ด ๊ธ€์„ ํ•œ๋ฒˆ ์ฐธ๊ณ ํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ๊ฐ™์•„์š”! ๐Ÿ‘
@@ -0,0 +1,103 @@ +package christmas.util; + +import christmas.domain.type.Menu; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class OrderValidator { + private static final String LINE_SEPARATOR = System.lineSeparator(); + + private static final int MIN_AMOUNT = 1; + private static final int MAX_AMOUNT = 20; + private static final String INPUT_PATTERN = "([\\S]+-\\d+)(,\\s*[\\S]+-\\d+)*"; + private static final String INVALID_ORDER_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String BEVERAGE_ONLY_MESSAGE = "์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private static final String INVALID_ORDER_AMOUNT_MESSAGE = "๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— 1๊ฐœ์ด์ƒ, ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + private static final String MENU_NOT_EXIST_MESSAGE = "์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ฉ”๋‰ด์ž…๋‹ˆ๋‹ค."; + private static final String DUPLICATED_MENU_ORDER_MESSAGE = "์ค‘๋ณต๋œ ๋ฉ”๋‰ด ํ•ญ๋ชฉ์ด ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static void validateInput(String input) { + checkInputPattern(input); + checkInputPatternMore(input); + List<String> menuNames = parseMenuName(input); + checkDuplicated(menuNames); + + for (String menuName : menuNames) { + checkMenu(menuName); + } + } + + public static void validateOrder(Map<Menu, Integer> order) { + checkAmount(order); + checkBeverageOnly(order); + } + + private static void checkBeverageOnly(Map<Menu, Integer> order) { + if (order.keySet() + .stream() + .allMatch(menu -> menu.getCategory() == Menu.Category.BEVERAGE)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + BEVERAGE_ONLY_MESSAGE); + } + } + + private static void checkAmount(Map<Menu, Integer> order) { + int totalAmount = order.values() + .stream() + .mapToInt(Integer::intValue).sum(); + + if (totalAmount < MIN_AMOUNT || totalAmount > MAX_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + + for (Integer amount : order.values()) { + if (amount < MIN_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + } + } + + private static void checkMenu(String menuName) { + boolean menuExists = Arrays.stream(Menu.values()).anyMatch(menu -> menu.getName().equals(menuName)); + + if (!menuExists) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + MENU_NOT_EXIST_MESSAGE); + } + } + private static void checkDuplicated(List<String> menuNames) { + Set<String> uniqueMenuNames = new HashSet<>(); + + for (String name : menuNames) { + if (!uniqueMenuNames.add(name)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + DUPLICATED_MENU_ORDER_MESSAGE); + } + } + } + + private static void checkInputPattern(String input) { + if (input == null || !Pattern.matches(INPUT_PATTERN, input)) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + + private static List<String> parseMenuName(String input) { + List<String> menuNames = Arrays.stream(input.split(",")) + .map(order -> order.trim().split("-")[0].trim()) + .collect(Collectors.toList()); + + return menuNames; + } + + private static void checkInputPatternMore(String input) { + String[] items = input.split(","); + + for (String item : items) { + int count = StringUtil.countMatches(item, '-'); + if (count != 1) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + } + +}
Java
"," ๋‚˜ "-"๋„ ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ด๋ฒคํŠธ์— ๋”ฐ๋ผ ์ž…๋ ฅ๋ฐ›๋Š” ๋ฐฉ์‹์ด ๋ฐ”๋€” ์ˆ˜๋„ ์žˆ์ž–์•„์š” ๐Ÿ‘
@@ -0,0 +1,76 @@ +package christmas.domain.logic; + +import christmas.domain.type.Badge; +import christmas.domain.type.Menu; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +public class EventCalculatorTest { + + @Test + void isEligibleForEvent() { + assertTrue(EventCalculator.isEligibleForEvent(15000)); + assertFalse(EventCalculator.isEligibleForEvent(5000)); + } + + @Test + void calculateWeekdayDiscount_์ฃผ์ค‘_๋””์ €ํŠธ() { + Map<Menu, Integer> order = Map.of(Menu.CHOCOLATE_CAKE, 1); + int discount = EventCalculator.calculateWeekdayDiscount(3, order); + assertEquals(2023, discount); + } + + @Test + void calculateWeekdayDiscount_์ฃผ์ค‘_๋””์ €ํŠธ์—†์Œ() { + Map<Menu, Integer> order = Map.of(Menu.CAESAR_SALAD, 1, Menu.TAPAS, 1); + int discount = EventCalculator.calculateWeekdayDiscount(3, order); + assertEquals(0, discount); + } + + @Test + void calculateWeekendDiscount_์ฃผ๋ง_๋ฉ”์ธ() { + Map<Menu, Integer> order = Map.of(Menu.T_BONE_STEAK, 2, Menu.TAPAS, 1); + int discount = EventCalculator.calculateWeekendDiscount(4, order); + assertEquals(2023 * 2, discount); + } + + @Test + void calculateWeekendDiscount_์ฃผ๋ง_๋ฉ”์ธ์—†์Œ() { + Map<Menu, Integer> order = Map.of(Menu.ICE_CREAM, 1); + int discount = EventCalculator.calculateWeekendDiscount(4, order); + assertEquals(0, discount); + } + + @Test + void calculateSpecialDiscount_๋ณ„๋ฐ์ด() { + int discount = EventCalculator.calculateSpecialDiscount(25); + assertEquals(1000, discount); + } + + @Test + void calculateSpecialDiscount_๋ณ„๋ฐ์ด_์•„๋‹˜() { + int discount = EventCalculator.calculateSpecialDiscount(26); + assertEquals(0, discount); + } + + @Test + void calculateGiveawayEvent() { + Map<Menu, Integer> giveaway = EventCalculator.calculateGiveawayEvent(120000); + assertNotNull(giveaway); + assertTrue(giveaway.containsKey(Menu.CHAMPAGNE)); + assertEquals(1, giveaway.get(Menu.CHAMPAGNE)); + } + + @Test + void calculateBadge() { + assertEquals(Badge.SANTA, EventCalculator.calculateBadge(20000)); + assertEquals(Badge.SANTA, EventCalculator.calculateBadge(30000)); + assertEquals(Badge.TREE, EventCalculator.calculateBadge(15000)); + assertEquals(Badge.TREE, EventCalculator.calculateBadge(19999)); + assertEquals(Badge.STAR, EventCalculator.calculateBadge(7000)); + assertEquals(Badge.NONE, EventCalculator.calculateBadge(4000)); + } +}
Java
ํด๋ฆฐ์ฝ”๋“œ์— ๋‚˜์˜ค๋Š” ๋‚ด์šฉ์ธ๋ฐ ํ•œ ํ…Œ์ŠคํŠธ ๋ฉ”์„œ๋“œ ์•ˆ์— ์—ฌ๋Ÿฌ assert๋ฌธ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์ข‹์ง€ ์•Š๋‹ค๊ณ  ํ•ด์š”! ํ•ด๋‹น ๋ฉ”์„œ๋“œ์—์„œ@ParameterizedTest ์™€ @MethodSource๋ฅผ ์‚ฌ์šฉํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,20 @@ +package christmas.domain.logic; + +import christmas.domain.model.DecemberEvent; + +public class ChristmasEventCalculator { + public static int calculateChristmasDiscount(int date) { + int startDay = DecemberEvent.getEventStartDate(); + int discountPricePerDay = DecemberEvent.getDayDiscountPrice(); + int discountPriceOfFirstDay = DecemberEvent.getStartDiscountPrice(); + + if (date > DecemberEvent.CHRISTMAS_DAY) { + return 0; + } + + int daysUntilDate = date - startDay; + int totalDiscount = discountPriceOfFirstDay + (daysUntilDate * discountPricePerDay); + + return totalDiscount; + } +}
Java
์œ ํ‹ธ๋ฆฌํ‹ฐ ํด๋ž˜์Šค๋กœ ๋ณด์ด๋Š”๋ฐ ์ƒ์„ฑ์ž๋ฅผ private๋กœ ๋งŒ๋“œ๋Š”๊ฒŒ ์ข‹์•„๋ณด์—ฌ์š”! ๐Ÿ‘
@@ -0,0 +1,71 @@ +package christmas.domain.model; + +import christmas.domain.type.Menu; + +import java.util.*; + +public class DecemberEvent { + public static final int CHRISTMAS_DAY = 25; + private static final int EVENT_START_DATE = 1; + private static final int DAY_DISCOUNT_PRICE = 100; + private static final int START_DISCOUNT_PRICE = 1_000; + private static final int MIN_PRICE = 10_000; + private static final int WEEKDAY_DISCOUNT_PRICE = 2_023; + private static final int WEEKEND_DISCOUNT_PRICE = 2_023; + private static final Menu.Category WEEKDAY_DISCOUNT_CATEGORY = Menu.Category.DESSERT; + private static final Menu.Category WEEKEND_DISCOUNT_CATEGORY = Menu.Category.MAIN; + private static final List<Integer> WEEKEND_DATES = Arrays.asList(1, 2, 8, 9, 15, 16, 22, 23, 29, 30); + private static final List<Integer> STAR_DATES = Arrays.asList(3, 10, 17, 24, 25, 31); + private static final int SPECIAL_DISCOUNT_PRICE = 1_000; + private static final int GIVEAWAY_CONDITION_PRICE = 120_000; + private static final Map<Menu, Integer> GIVEAWAY_BENEFITS = Map.of(Menu.CHAMPAGNE, 1); + + + public static boolean isOverThanMinPrice(int totalPrice) { + return totalPrice >= MIN_PRICE; + } + + public static boolean isStarDate(int date) { + return STAR_DATES.contains(date); + } + + public static boolean isWeekend(int date) { + return WEEKEND_DATES.contains(date); + } + + public static boolean isEligibleForGiveaway(int totalPrice) { + return totalPrice >= GIVEAWAY_CONDITION_PRICE; + } + + public static int getSpecialDiscountPrice() { + return SPECIAL_DISCOUNT_PRICE; + } + + public static int getWeekdayDiscountPrice() { return WEEKDAY_DISCOUNT_PRICE; } + + public static int getWeekendDiscountPrice() { return WEEKEND_DISCOUNT_PRICE; } + + public static Menu.Category getWeekdayDiscountCategory() { + return WEEKDAY_DISCOUNT_CATEGORY; + } + + public static Menu.Category getWeekendDiscountCategory() { + return WEEKEND_DISCOUNT_CATEGORY; + } + + public static Map<Menu, Integer> getGiveawayBenefits() { + return GIVEAWAY_BENEFITS; + } + + public static int getDayDiscountPrice() { + return DAY_DISCOUNT_PRICE; + } + + public static int getStartDiscountPrice() { + return START_DISCOUNT_PRICE; + } + + public static int getEventStartDate() { + return EVENT_START_DATE; + } +}
Java
์ƒ์ˆ˜๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋‹ค๋ฅธ ํŒจํ‚ค์ง€๋กœ ๊ตฌ๋ถ„ํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,103 @@ +package christmas.util; + +import christmas.domain.type.Menu; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class OrderValidator { + private static final String LINE_SEPARATOR = System.lineSeparator(); + + private static final int MIN_AMOUNT = 1; + private static final int MAX_AMOUNT = 20; + private static final String INPUT_PATTERN = "([\\S]+-\\d+)(,\\s*[\\S]+-\\d+)*"; + private static final String INVALID_ORDER_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String BEVERAGE_ONLY_MESSAGE = "์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private static final String INVALID_ORDER_AMOUNT_MESSAGE = "๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— 1๊ฐœ์ด์ƒ, ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + private static final String MENU_NOT_EXIST_MESSAGE = "์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ฉ”๋‰ด์ž…๋‹ˆ๋‹ค."; + private static final String DUPLICATED_MENU_ORDER_MESSAGE = "์ค‘๋ณต๋œ ๋ฉ”๋‰ด ํ•ญ๋ชฉ์ด ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static void validateInput(String input) { + checkInputPattern(input); + checkInputPatternMore(input); + List<String> menuNames = parseMenuName(input); + checkDuplicated(menuNames); + + for (String menuName : menuNames) { + checkMenu(menuName); + } + } + + public static void validateOrder(Map<Menu, Integer> order) { + checkAmount(order); + checkBeverageOnly(order); + } + + private static void checkBeverageOnly(Map<Menu, Integer> order) { + if (order.keySet() + .stream() + .allMatch(menu -> menu.getCategory() == Menu.Category.BEVERAGE)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + BEVERAGE_ONLY_MESSAGE); + } + } + + private static void checkAmount(Map<Menu, Integer> order) { + int totalAmount = order.values() + .stream() + .mapToInt(Integer::intValue).sum(); + + if (totalAmount < MIN_AMOUNT || totalAmount > MAX_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + + for (Integer amount : order.values()) { + if (amount < MIN_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + } + } + + private static void checkMenu(String menuName) { + boolean menuExists = Arrays.stream(Menu.values()).anyMatch(menu -> menu.getName().equals(menuName)); + + if (!menuExists) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + MENU_NOT_EXIST_MESSAGE); + } + } + private static void checkDuplicated(List<String> menuNames) { + Set<String> uniqueMenuNames = new HashSet<>(); + + for (String name : menuNames) { + if (!uniqueMenuNames.add(name)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + DUPLICATED_MENU_ORDER_MESSAGE); + } + } + } + + private static void checkInputPattern(String input) { + if (input == null || !Pattern.matches(INPUT_PATTERN, input)) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + + private static List<String> parseMenuName(String input) { + List<String> menuNames = Arrays.stream(input.split(",")) + .map(order -> order.trim().split("-")[0].trim()) + .collect(Collectors.toList()); + + return menuNames; + } + + private static void checkInputPatternMore(String input) { + String[] items = input.split(","); + + for (String item : items) { + int count = StringUtil.countMatches(item, '-'); + if (count != 1) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + } + +}
Java
getter๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋Œ€์‹  menu๊ฐ์ฒด๊ฐ€ ์ง์ ‘ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ๋น„๊ตํ•˜๊ฒŒ ํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,61 @@ +package christmas.view; + +import camp.nextstep.edu.missionutils.Console; +import christmas.domain.type.Menu; +import christmas.util.DateValidator; +import christmas.util.OrderValidator; +import christmas.util.ValidationException; + +import java.util.HashMap; +import java.util.Map; + +public class InputView { + private static final String ASK_DATE_MESSAGE = "12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"; + private static final String ASK_ORDER_MESSAGE = "์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"; + + public int readDate() { + while (true) { + try { + System.out.println(ASK_DATE_MESSAGE); + String input = Console.readLine(); + DateValidator.validateInput(input); + int date = Integer.parseInt(input); + return date; + } catch (ValidationException e) { + System.out.println(e.getMessage()); + } + } + } + + public Map<Menu, Integer> readOrder() { + while (true) { + try { + System.out.println(ASK_ORDER_MESSAGE); + String input = Console.readLine(); + OrderValidator.validateInput(input); + Map<Menu, Integer> order = parseOrder(input); + OrderValidator.validateOrder(order); + + return order; + } catch (ValidationException e) { + System.out.println(e.getMessage()); + } + } + } + + private Map<Menu, Integer> parseOrder(String input) { + Map<Menu, Integer> order = new HashMap<>(); + + String[] items = input.split(","); + for (String item : items) { + String[] parts = item.trim() + .split("-"); + String menuName = parts[0].trim(); + int amount = Integer.parseInt(parts[1].trim()); + + Menu menu = Menu.findByName(menuName); + order.put(menu, amount); + } + return order; + } +}
Java
๋ฐ˜๋ณต๋˜์ง€๋งŒ ๋ฏธ์„ธํ•˜๊ฒŒ ๋‹ค๋ฅธ ์ฝ”๋“œ๋„ค์š”! ์–ด๋–ป๊ฒŒ ๋ฐ˜๋ณต์„ ์ค„์ผ์ง€ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ๐Ÿ‘
@@ -0,0 +1,103 @@ +package christmas.util; + +import christmas.domain.type.Menu; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class OrderValidator { + private static final String LINE_SEPARATOR = System.lineSeparator(); + + private static final int MIN_AMOUNT = 1; + private static final int MAX_AMOUNT = 20; + private static final String INPUT_PATTERN = "([\\S]+-\\d+)(,\\s*[\\S]+-\\d+)*"; + private static final String INVALID_ORDER_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String BEVERAGE_ONLY_MESSAGE = "์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private static final String INVALID_ORDER_AMOUNT_MESSAGE = "๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— 1๊ฐœ์ด์ƒ, ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + private static final String MENU_NOT_EXIST_MESSAGE = "์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ฉ”๋‰ด์ž…๋‹ˆ๋‹ค."; + private static final String DUPLICATED_MENU_ORDER_MESSAGE = "์ค‘๋ณต๋œ ๋ฉ”๋‰ด ํ•ญ๋ชฉ์ด ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static void validateInput(String input) { + checkInputPattern(input); + checkInputPatternMore(input); + List<String> menuNames = parseMenuName(input); + checkDuplicated(menuNames); + + for (String menuName : menuNames) { + checkMenu(menuName); + } + } + + public static void validateOrder(Map<Menu, Integer> order) { + checkAmount(order); + checkBeverageOnly(order); + } + + private static void checkBeverageOnly(Map<Menu, Integer> order) { + if (order.keySet() + .stream() + .allMatch(menu -> menu.getCategory() == Menu.Category.BEVERAGE)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + BEVERAGE_ONLY_MESSAGE); + } + } + + private static void checkAmount(Map<Menu, Integer> order) { + int totalAmount = order.values() + .stream() + .mapToInt(Integer::intValue).sum(); + + if (totalAmount < MIN_AMOUNT || totalAmount > MAX_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + + for (Integer amount : order.values()) { + if (amount < MIN_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + } + } + + private static void checkMenu(String menuName) { + boolean menuExists = Arrays.stream(Menu.values()).anyMatch(menu -> menu.getName().equals(menuName)); + + if (!menuExists) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + MENU_NOT_EXIST_MESSAGE); + } + } + private static void checkDuplicated(List<String> menuNames) { + Set<String> uniqueMenuNames = new HashSet<>(); + + for (String name : menuNames) { + if (!uniqueMenuNames.add(name)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + DUPLICATED_MENU_ORDER_MESSAGE); + } + } + } + + private static void checkInputPattern(String input) { + if (input == null || !Pattern.matches(INPUT_PATTERN, input)) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + + private static List<String> parseMenuName(String input) { + List<String> menuNames = Arrays.stream(input.split(",")) + .map(order -> order.trim().split("-")[0].trim()) + .collect(Collectors.toList()); + + return menuNames; + } + + private static void checkInputPatternMore(String input) { + String[] items = input.split(","); + + for (String item : items) { + int count = StringUtil.countMatches(item, '-'); + if (count != 1) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + } + +}
Java
throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + ******); ์ด๋ถ€๋ถ„์ด ๋ฐ˜๋ณต๋˜๋„ค์š”! ์ €๋Š” ๋ฉ”์„œ๋“œ๋‚˜ ์ƒ์ˆ˜๋กœ ๋ฐ˜๋ณต์„ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ค๊ฐ€์š”? ๐Ÿ‘
@@ -0,0 +1,28 @@ +package christmas.util; + +public class DateValidator { + private static final String INVALID_DATE_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + public static void validateInput(String input) { + validateNumeric(input); + int date = Integer.parseInt(input); + validateDate(date); + } + + private static void validateNumeric(String input) { + if (input == null) { + throw new ValidationException(INVALID_DATE_MESSAGE); + } + try { + Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new ValidationException(INVALID_DATE_MESSAGE); + } + } + + private static void validateDate(int date) { + if (date < 1 || date > 31) { + throw new ValidationException(INVALID_DATE_MESSAGE); + } + } +}
Java
์•„ ๋งž๋„ค์š” ์ œ๊ฐ€ ์ถ”๊ตฌํ•˜๋Š” ๋ฐฉํ–ฅ์ด `12์›” ์ด๋ฒคํŠธ` ํด๋ž˜์Šค๋งŒ ๋งค๋‹ฌ ํ•ด๋‹นํ•˜๋Š” ๋‹ฌ์— ๊ฐˆ์•„ ๋ผ์šฐ๋Š” ๊ฑฐ์˜€๊ฑฐ๋“ ์š” `๋ช‡์›”.LAST_DATE` ์ด๋Ÿฐ์‹์œผ๋กœ ๋ฐ”๊ฟ”์•ผ ๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,76 @@ +package christmas.domain.logic; + +import christmas.domain.type.Badge; +import christmas.domain.type.Menu; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +public class EventCalculatorTest { + + @Test + void isEligibleForEvent() { + assertTrue(EventCalculator.isEligibleForEvent(15000)); + assertFalse(EventCalculator.isEligibleForEvent(5000)); + } + + @Test + void calculateWeekdayDiscount_์ฃผ์ค‘_๋””์ €ํŠธ() { + Map<Menu, Integer> order = Map.of(Menu.CHOCOLATE_CAKE, 1); + int discount = EventCalculator.calculateWeekdayDiscount(3, order); + assertEquals(2023, discount); + } + + @Test + void calculateWeekdayDiscount_์ฃผ์ค‘_๋””์ €ํŠธ์—†์Œ() { + Map<Menu, Integer> order = Map.of(Menu.CAESAR_SALAD, 1, Menu.TAPAS, 1); + int discount = EventCalculator.calculateWeekdayDiscount(3, order); + assertEquals(0, discount); + } + + @Test + void calculateWeekendDiscount_์ฃผ๋ง_๋ฉ”์ธ() { + Map<Menu, Integer> order = Map.of(Menu.T_BONE_STEAK, 2, Menu.TAPAS, 1); + int discount = EventCalculator.calculateWeekendDiscount(4, order); + assertEquals(2023 * 2, discount); + } + + @Test + void calculateWeekendDiscount_์ฃผ๋ง_๋ฉ”์ธ์—†์Œ() { + Map<Menu, Integer> order = Map.of(Menu.ICE_CREAM, 1); + int discount = EventCalculator.calculateWeekendDiscount(4, order); + assertEquals(0, discount); + } + + @Test + void calculateSpecialDiscount_๋ณ„๋ฐ์ด() { + int discount = EventCalculator.calculateSpecialDiscount(25); + assertEquals(1000, discount); + } + + @Test + void calculateSpecialDiscount_๋ณ„๋ฐ์ด_์•„๋‹˜() { + int discount = EventCalculator.calculateSpecialDiscount(26); + assertEquals(0, discount); + } + + @Test + void calculateGiveawayEvent() { + Map<Menu, Integer> giveaway = EventCalculator.calculateGiveawayEvent(120000); + assertNotNull(giveaway); + assertTrue(giveaway.containsKey(Menu.CHAMPAGNE)); + assertEquals(1, giveaway.get(Menu.CHAMPAGNE)); + } + + @Test + void calculateBadge() { + assertEquals(Badge.SANTA, EventCalculator.calculateBadge(20000)); + assertEquals(Badge.SANTA, EventCalculator.calculateBadge(30000)); + assertEquals(Badge.TREE, EventCalculator.calculateBadge(15000)); + assertEquals(Badge.TREE, EventCalculator.calculateBadge(19999)); + assertEquals(Badge.STAR, EventCalculator.calculateBadge(7000)); + assertEquals(Badge.NONE, EventCalculator.calculateBadge(4000)); + } +}
Java
์˜ค... ์•„์ง ํ…Œ์ŠคํŠธ์ฝ”๋“œ๊ฐ€ ์ต์ˆ™์น˜์•Š์•˜๋Š”๋ฐ ํ™œ์šฉํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,20 @@ +package christmas.domain.logic; + +import christmas.domain.model.DecemberEvent; + +public class ChristmasEventCalculator { + public static int calculateChristmasDiscount(int date) { + int startDay = DecemberEvent.getEventStartDate(); + int discountPricePerDay = DecemberEvent.getDayDiscountPrice(); + int discountPriceOfFirstDay = DecemberEvent.getStartDiscountPrice(); + + if (date > DecemberEvent.CHRISTMAS_DAY) { + return 0; + } + + int daysUntilDate = date - startDay; + int totalDiscount = discountPriceOfFirstDay + (daysUntilDate * discountPricePerDay); + + return totalDiscount; + } +}
Java
์•„ํ•˜ ๊ตณ์ด ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋  ํ•„์š”๊ฐ€ ์—†๊ตฐ์š”
@@ -0,0 +1,71 @@ +package christmas.domain.model; + +import christmas.domain.type.Menu; + +import java.util.*; + +public class DecemberEvent { + public static final int CHRISTMAS_DAY = 25; + private static final int EVENT_START_DATE = 1; + private static final int DAY_DISCOUNT_PRICE = 100; + private static final int START_DISCOUNT_PRICE = 1_000; + private static final int MIN_PRICE = 10_000; + private static final int WEEKDAY_DISCOUNT_PRICE = 2_023; + private static final int WEEKEND_DISCOUNT_PRICE = 2_023; + private static final Menu.Category WEEKDAY_DISCOUNT_CATEGORY = Menu.Category.DESSERT; + private static final Menu.Category WEEKEND_DISCOUNT_CATEGORY = Menu.Category.MAIN; + private static final List<Integer> WEEKEND_DATES = Arrays.asList(1, 2, 8, 9, 15, 16, 22, 23, 29, 30); + private static final List<Integer> STAR_DATES = Arrays.asList(3, 10, 17, 24, 25, 31); + private static final int SPECIAL_DISCOUNT_PRICE = 1_000; + private static final int GIVEAWAY_CONDITION_PRICE = 120_000; + private static final Map<Menu, Integer> GIVEAWAY_BENEFITS = Map.of(Menu.CHAMPAGNE, 1); + + + public static boolean isOverThanMinPrice(int totalPrice) { + return totalPrice >= MIN_PRICE; + } + + public static boolean isStarDate(int date) { + return STAR_DATES.contains(date); + } + + public static boolean isWeekend(int date) { + return WEEKEND_DATES.contains(date); + } + + public static boolean isEligibleForGiveaway(int totalPrice) { + return totalPrice >= GIVEAWAY_CONDITION_PRICE; + } + + public static int getSpecialDiscountPrice() { + return SPECIAL_DISCOUNT_PRICE; + } + + public static int getWeekdayDiscountPrice() { return WEEKDAY_DISCOUNT_PRICE; } + + public static int getWeekendDiscountPrice() { return WEEKEND_DISCOUNT_PRICE; } + + public static Menu.Category getWeekdayDiscountCategory() { + return WEEKDAY_DISCOUNT_CATEGORY; + } + + public static Menu.Category getWeekendDiscountCategory() { + return WEEKEND_DISCOUNT_CATEGORY; + } + + public static Map<Menu, Integer> getGiveawayBenefits() { + return GIVEAWAY_BENEFITS; + } + + public static int getDayDiscountPrice() { + return DAY_DISCOUNT_PRICE; + } + + public static int getStartDiscountPrice() { + return START_DISCOUNT_PRICE; + } + + public static int getEventStartDate() { + return EVENT_START_DATE; + } +}
Java
12์›” ์ด๋ฒคํŠธ์—๋Š” ํ• ์ธ ๊ธˆ์•ก์ด๋‚˜ ๊ธฐ๊ฐ„๋“ฑ์ด ์žˆ์–ด์„œ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง๊ณผ ๋ฐ€์ ‘ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ์ €๊ธฐ์— ์œ„์น˜ํ•˜๊ธด ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,103 @@ +package christmas.util; + +import christmas.domain.type.Menu; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class OrderValidator { + private static final String LINE_SEPARATOR = System.lineSeparator(); + + private static final int MIN_AMOUNT = 1; + private static final int MAX_AMOUNT = 20; + private static final String INPUT_PATTERN = "([\\S]+-\\d+)(,\\s*[\\S]+-\\d+)*"; + private static final String INVALID_ORDER_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String BEVERAGE_ONLY_MESSAGE = "์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private static final String INVALID_ORDER_AMOUNT_MESSAGE = "๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— 1๊ฐœ์ด์ƒ, ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + private static final String MENU_NOT_EXIST_MESSAGE = "์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ฉ”๋‰ด์ž…๋‹ˆ๋‹ค."; + private static final String DUPLICATED_MENU_ORDER_MESSAGE = "์ค‘๋ณต๋œ ๋ฉ”๋‰ด ํ•ญ๋ชฉ์ด ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static void validateInput(String input) { + checkInputPattern(input); + checkInputPatternMore(input); + List<String> menuNames = parseMenuName(input); + checkDuplicated(menuNames); + + for (String menuName : menuNames) { + checkMenu(menuName); + } + } + + public static void validateOrder(Map<Menu, Integer> order) { + checkAmount(order); + checkBeverageOnly(order); + } + + private static void checkBeverageOnly(Map<Menu, Integer> order) { + if (order.keySet() + .stream() + .allMatch(menu -> menu.getCategory() == Menu.Category.BEVERAGE)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + BEVERAGE_ONLY_MESSAGE); + } + } + + private static void checkAmount(Map<Menu, Integer> order) { + int totalAmount = order.values() + .stream() + .mapToInt(Integer::intValue).sum(); + + if (totalAmount < MIN_AMOUNT || totalAmount > MAX_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + + for (Integer amount : order.values()) { + if (amount < MIN_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + } + } + + private static void checkMenu(String menuName) { + boolean menuExists = Arrays.stream(Menu.values()).anyMatch(menu -> menu.getName().equals(menuName)); + + if (!menuExists) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + MENU_NOT_EXIST_MESSAGE); + } + } + private static void checkDuplicated(List<String> menuNames) { + Set<String> uniqueMenuNames = new HashSet<>(); + + for (String name : menuNames) { + if (!uniqueMenuNames.add(name)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + DUPLICATED_MENU_ORDER_MESSAGE); + } + } + } + + private static void checkInputPattern(String input) { + if (input == null || !Pattern.matches(INPUT_PATTERN, input)) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + + private static List<String> parseMenuName(String input) { + List<String> menuNames = Arrays.stream(input.split(",")) + .map(order -> order.trim().split("-")[0].trim()) + .collect(Collectors.toList()); + + return menuNames; + } + + private static void checkInputPatternMore(String input) { + String[] items = input.split(","); + + for (String item : items) { + int count = StringUtil.countMatches(item, '-'); + if (count != 1) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + } + +}
Java
ํ•ด๋‹น ๊ทœ์น™์— ๋Œ€ํ•œ ์ฑ…์ž„์€ ๋ฉ”๋‰ด๋ณด๋‹ค๋Š” ์ฃผ๋ฌธ๊ฒ€์ฆ์— ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ์ €๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜๊ธด ํ–ˆ๋Š”๋ฐ ๋ฉ”๋‰ด๊ฐ€ ์Šค์Šค๋กœ ํŒ๋‹จ ํ•  ์ˆ˜ ์žˆ๋Š”๊ฒƒ์„ ์ข€๋” ๊ตฌ๋ถ„ํ•ด๋†“์œผ๋ฉด ๋” ์ข‹์•„์ง€๊ฒ ๋„ค์š”!
@@ -0,0 +1,41 @@ +package christmas.domain.model; + +import christmas.domain.type.Menu; + +import java.util.Map; + +public class OrderInfo { + private final int date; + private final Map<Menu, Integer> order; + private final int totalOrderPrice; + + public OrderInfo(int date, Map<Menu, Integer> order) { + this.date = date; + this.order = order; + this.totalOrderPrice = calculateTotalOrderPrice(); + } + + public int getDate() { + return date; + } + public Map<Menu, Integer> getOrder() { + return order; + } + + public int getTotalOrderPrice() { + return totalOrderPrice; + } + + private int calculateTotalOrderPrice() { + int totalOrderPrice = 0; + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalOrderPrice += menu.getPrice() * quantity; + } + + return totalOrderPrice; + } +}
Java
calculateTotalOrderPrice๋กœ ํ•ญ์ƒ ๊ฐ’์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์œผ๋‹ˆ totalOrderPrice๋ฅผ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋กœ ๊ฐ–๋Š” ๊ฒƒ ๋ณด๋‹ค ์™ธ๋ถ€์—์„œ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹์€ ์–ด๋– ์‹ ๊ฐ€์š”?
@@ -0,0 +1,58 @@ +package christmas.domain.type; + +public enum Menu { + //์—ํ”ผํƒ€์ด์ € + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, Category.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, Category.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, Category.APPETIZER), + + //๋ฉ”์ธ + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, Category.MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, Category.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, Category.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, Category.MAIN), + + //๋””์ €ํŠธ + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, Category.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, Category.DESSERT), + + //์Œ๋ฃŒ + ZERO_COKE("์ œ๋กœ์ฝœ๋ผ", 3_000, Category.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, Category.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, Category.BEVERAGE); + + private final String name; + private final int price; + private final Category category; + + Menu(String name, int price, Category category) { + this.name = name; + this.price = price; + this.category = category; + } + + public static Menu findByName(String menuName) { + for (Menu menu : Menu.values()) { + if (menu.getName().equals(menuName)) { + return menu; + } + } + return null; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public Category getCategory() { + return category; + } + + public enum Category { + APPETIZER, MAIN, DESSERT, BEVERAGE + } +}
Java
์ž๋ฐ” ์ŠคํŠธ๋ฆผ api ๋ฅผ ์‚ฌ์šฉํ•˜์‹œ๋ฉด ์ธ๋ดํŠธ๋ฅผ ์ค„์ด๊ณ  ๋ช…ํ™•์„ฑ์„ ๋†’์ด์‹ค ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,58 @@ +package christmas.domain.type; + +public enum Menu { + //์—ํ”ผํƒ€์ด์ € + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, Category.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, Category.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, Category.APPETIZER), + + //๋ฉ”์ธ + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, Category.MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, Category.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, Category.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, Category.MAIN), + + //๋””์ €ํŠธ + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, Category.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, Category.DESSERT), + + //์Œ๋ฃŒ + ZERO_COKE("์ œ๋กœ์ฝœ๋ผ", 3_000, Category.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, Category.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, Category.BEVERAGE); + + private final String name; + private final int price; + private final Category category; + + Menu(String name, int price, Category category) { + this.name = name; + this.price = price; + this.category = category; + } + + public static Menu findByName(String menuName) { + for (Menu menu : Menu.values()) { + if (menu.getName().equals(menuName)) { + return menu; + } + } + return null; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public Category getCategory() { + return category; + } + + public enum Category { + APPETIZER, MAIN, DESSERT, BEVERAGE + } +}
Java
InputView์—์„œ๋„ ๋น„์Šทํ•œ ์ฝ”๋“œ๋กœ ๋ฉ”๋‰ด ์ด๋ฆ„์„ ๊ฒ€์ฆํ•˜์‹œ๋Š”๋ฐ null ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋Œ€์‹  ์—ฌ๊ธฐ์„œ ๋ฐ”๋กœ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€์‹œ๋Š” ๊ฑด ์–ด๋– ์‹ ๊ฐ€์š”?
@@ -0,0 +1,70 @@ +package christmas.domain.logic; + +import christmas.domain.model.DecemberEvent; +import christmas.domain.type.Badge; +import christmas.domain.type.Menu; + +import java.util.Collections; +import java.util.Map; + +public class EventCalculator { + public static boolean isEligibleForEvent(int totalPrice) { + return DecemberEvent.isOverThanMinPrice(totalPrice); + } + + public static int calculateWeekdayDiscount(int date, Map<Menu, Integer> order) { + int totalDiscount = 0; + Menu.Category category = DecemberEvent.getWeekdayDiscountCategory(); + int discountPrice = DecemberEvent.getWeekdayDiscountPrice(); + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalDiscount += calculateDiscountByCategory(menu, quantity, category, discountPrice); + } + + return totalDiscount; + } + + public static int calculateWeekendDiscount(int date, Map<Menu, Integer> order) { + int totalDiscount = 0; + Menu.Category category = DecemberEvent.getWeekendDiscountCategory(); + int discountPrice = DecemberEvent.getWeekendDiscountPrice(); + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalDiscount += calculateDiscountByCategory(menu, quantity, category, discountPrice); + } + + return totalDiscount; + } + + public static int calculateSpecialDiscount(int date) { + if (DecemberEvent.isStarDate(date)) { + return DecemberEvent.getSpecialDiscountPrice(); + } + return 0; + } + + public static Map<Menu, Integer> calculateGiveawayEvent(int totalPrice) { + if (DecemberEvent.isEligibleForGiveaway(totalPrice)) { + return DecemberEvent.getGiveawayBenefits(); + } + return Collections.emptyMap(); + } + + public static Badge calculateBadge(int totalDiscount) { + Badge badge = Badge.findByTotalDiscount(totalDiscount); + return badge; + } + + private static int calculateDiscountByCategory(Menu menu, int quantity, Menu.Category category, int discountPrice) { + if (menu.getCategory().equals(category)) { + return quantity * discountPrice; + } + return 0; + } +}
Java
์ด ๋ฉ”์„œ๋“œ์—์„œ date๋Š” ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋ฐ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์œผ์‹œ๋Š” ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,70 @@ +package christmas.domain.logic; + +import christmas.domain.model.DecemberEvent; +import christmas.domain.type.Badge; +import christmas.domain.type.Menu; + +import java.util.Collections; +import java.util.Map; + +public class EventCalculator { + public static boolean isEligibleForEvent(int totalPrice) { + return DecemberEvent.isOverThanMinPrice(totalPrice); + } + + public static int calculateWeekdayDiscount(int date, Map<Menu, Integer> order) { + int totalDiscount = 0; + Menu.Category category = DecemberEvent.getWeekdayDiscountCategory(); + int discountPrice = DecemberEvent.getWeekdayDiscountPrice(); + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalDiscount += calculateDiscountByCategory(menu, quantity, category, discountPrice); + } + + return totalDiscount; + } + + public static int calculateWeekendDiscount(int date, Map<Menu, Integer> order) { + int totalDiscount = 0; + Menu.Category category = DecemberEvent.getWeekendDiscountCategory(); + int discountPrice = DecemberEvent.getWeekendDiscountPrice(); + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalDiscount += calculateDiscountByCategory(menu, quantity, category, discountPrice); + } + + return totalDiscount; + } + + public static int calculateSpecialDiscount(int date) { + if (DecemberEvent.isStarDate(date)) { + return DecemberEvent.getSpecialDiscountPrice(); + } + return 0; + } + + public static Map<Menu, Integer> calculateGiveawayEvent(int totalPrice) { + if (DecemberEvent.isEligibleForGiveaway(totalPrice)) { + return DecemberEvent.getGiveawayBenefits(); + } + return Collections.emptyMap(); + } + + public static Badge calculateBadge(int totalDiscount) { + Badge badge = Badge.findByTotalDiscount(totalDiscount); + return badge; + } + + private static int calculateDiscountByCategory(Menu menu, int quantity, Menu.Category category, int discountPrice) { + if (menu.getCategory().equals(category)) { + return quantity * discountPrice; + } + return 0; + } +}
Java
Map<Menu, Integer> order ๋กœ ์นดํ…Œ์ฝ”๋ฆฌ๋ณ„ ๋ฉ”๋‰ด ๊ฐœ์ˆ˜๋ฅผ ์…€ ์ˆ˜ ์žˆ์œผ๋‹ˆ ์ด๋ฅผ OrderInfo ๋ชจ๋ธ์˜ ์—ญํ• ๋กœ ๋„˜๊ธฐ์‹œ๋Š” ๊ฑด ์–ด๋– ์‹ค๊นŒ์š”?
@@ -0,0 +1,61 @@ +package christmas.domain.model; + +import christmas.domain.type.Badge; +import christmas.domain.type.Benefit; + +import java.util.Map; + +public class EventResult { + private final OrderInfo orderInfo; + private final Map<Benefit, Integer> benefitHistory; + private final int totalBenefitsPrice; + private final int finalPrice; + private final Badge badge; + + public EventResult(OrderInfo orderInfo, Map<Benefit, Integer> benefitHistory, int totalBenefitsPrice, Badge badge) { + this.orderInfo = orderInfo; + this.benefitHistory = benefitHistory; + this.totalBenefitsPrice = totalBenefitsPrice; + this.finalPrice = calculateFinalPrice(); + this.badge = badge; + } + + // getter + public OrderInfo getOrder() { + return orderInfo; + } + + public Map<Benefit, Integer> getBenefitHistory() { + return benefitHistory; + } + + public int getTotalBenefitsPrice() { + return totalBenefitsPrice; + } + + public int getFinalPrice() { + return finalPrice; + } + + public Badge getBadge() { + return badge; + } + + public boolean hasGiveawayBenefits() { + if (benefitHistory.containsKey(Benefit.GIVEAWAY)) { + return true; + } + return false; + } + + //private ํ—ฌํผ + private int calculateFinalPrice() { + int finalPrice = orderInfo.getTotalOrderPrice() - totalBenefitsPrice; + + if (benefitHistory.containsKey(Benefit.GIVEAWAY)) { + finalPrice += benefitHistory.get(Benefit.GIVEAWAY); + } + + return finalPrice; + } +}
Java
EventResult๋Š” dto๋กœ ์‚ฌ์šฉํ•˜์‹ ๊ฑธ๊นŒ์š”?
@@ -0,0 +1,103 @@ +package christmas.util; + +import christmas.domain.type.Menu; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class OrderValidator { + private static final String LINE_SEPARATOR = System.lineSeparator(); + + private static final int MIN_AMOUNT = 1; + private static final int MAX_AMOUNT = 20; + private static final String INPUT_PATTERN = "([\\S]+-\\d+)(,\\s*[\\S]+-\\d+)*"; + private static final String INVALID_ORDER_MESSAGE = "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String BEVERAGE_ONLY_MESSAGE = "์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private static final String INVALID_ORDER_AMOUNT_MESSAGE = "๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— 1๊ฐœ์ด์ƒ, ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + private static final String MENU_NOT_EXIST_MESSAGE = "์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ฉ”๋‰ด์ž…๋‹ˆ๋‹ค."; + private static final String DUPLICATED_MENU_ORDER_MESSAGE = "์ค‘๋ณต๋œ ๋ฉ”๋‰ด ํ•ญ๋ชฉ์ด ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static void validateInput(String input) { + checkInputPattern(input); + checkInputPatternMore(input); + List<String> menuNames = parseMenuName(input); + checkDuplicated(menuNames); + + for (String menuName : menuNames) { + checkMenu(menuName); + } + } + + public static void validateOrder(Map<Menu, Integer> order) { + checkAmount(order); + checkBeverageOnly(order); + } + + private static void checkBeverageOnly(Map<Menu, Integer> order) { + if (order.keySet() + .stream() + .allMatch(menu -> menu.getCategory() == Menu.Category.BEVERAGE)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + BEVERAGE_ONLY_MESSAGE); + } + } + + private static void checkAmount(Map<Menu, Integer> order) { + int totalAmount = order.values() + .stream() + .mapToInt(Integer::intValue).sum(); + + if (totalAmount < MIN_AMOUNT || totalAmount > MAX_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + + for (Integer amount : order.values()) { + if (amount < MIN_AMOUNT) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + INVALID_ORDER_AMOUNT_MESSAGE); + } + } + } + + private static void checkMenu(String menuName) { + boolean menuExists = Arrays.stream(Menu.values()).anyMatch(menu -> menu.getName().equals(menuName)); + + if (!menuExists) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + MENU_NOT_EXIST_MESSAGE); + } + } + private static void checkDuplicated(List<String> menuNames) { + Set<String> uniqueMenuNames = new HashSet<>(); + + for (String name : menuNames) { + if (!uniqueMenuNames.add(name)) { + throw new ValidationException(INVALID_ORDER_MESSAGE + LINE_SEPARATOR + DUPLICATED_MENU_ORDER_MESSAGE); + } + } + } + + private static void checkInputPattern(String input) { + if (input == null || !Pattern.matches(INPUT_PATTERN, input)) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + + private static List<String> parseMenuName(String input) { + List<String> menuNames = Arrays.stream(input.split(",")) + .map(order -> order.trim().split("-")[0].trim()) + .collect(Collectors.toList()); + + return menuNames; + } + + private static void checkInputPatternMore(String input) { + String[] items = input.split(","); + + for (String item : items) { + int count = StringUtil.countMatches(item, '-'); + if (count != 1) { + throw new ValidationException(INVALID_ORDER_MESSAGE); + } + } + } + +}
Java
More ๋ณด๋‹ค ๋ฉ”์„œ๋“œ ์˜๋„๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฉ”์„œ๋“œ๋ช…์„ ์‚ฌ์šฉํ•˜์‹œ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,41 @@ +package christmas.domain.model; + +import christmas.domain.type.Menu; + +import java.util.Map; + +public class OrderInfo { + private final int date; + private final Map<Menu, Integer> order; + private final int totalOrderPrice; + + public OrderInfo(int date, Map<Menu, Integer> order) { + this.date = date; + this.order = order; + this.totalOrderPrice = calculateTotalOrderPrice(); + } + + public int getDate() { + return date; + } + public Map<Menu, Integer> getOrder() { + return order; + } + + public int getTotalOrderPrice() { + return totalOrderPrice; + } + + private int calculateTotalOrderPrice() { + int totalOrderPrice = 0; + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalOrderPrice += menu.getPrice() * quantity; + } + + return totalOrderPrice; + } +}
Java
์ž์‹ ์ด ๊ฐ€์ง„ ๊ฐ’์œผ๋กœ ํ•œ๋ฒˆ ์ •ํ•ด์ง€๊ณ  ๋ณ€ํ•˜์ง€ ์•Š๋Š” ๊ฐ’์ด์–ด์„œ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค! orderInfo์˜ ๊ฐ’์€ ๋‹ค๋ฅธ ๊ณณ์—์„œ ํ™œ์šฉ๋ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,58 @@ +package christmas.domain.type; + +public enum Menu { + //์—ํ”ผํƒ€์ด์ € + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, Category.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, Category.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, Category.APPETIZER), + + //๋ฉ”์ธ + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, Category.MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, Category.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, Category.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, Category.MAIN), + + //๋””์ €ํŠธ + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, Category.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, Category.DESSERT), + + //์Œ๋ฃŒ + ZERO_COKE("์ œ๋กœ์ฝœ๋ผ", 3_000, Category.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, Category.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, Category.BEVERAGE); + + private final String name; + private final int price; + private final Category category; + + Menu(String name, int price, Category category) { + this.name = name; + this.price = price; + this.category = category; + } + + public static Menu findByName(String menuName) { + for (Menu menu : Menu.values()) { + if (menu.getName().equals(menuName)) { + return menu; + } + } + return null; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public Category getCategory() { + return category; + } + + public enum Category { + APPETIZER, MAIN, DESSERT, BEVERAGE + } +}
Java
๋‹ค์Šฌ๋‹˜ ์ฝ”๋“œ์—์„œ ํ•œ์ˆ˜ ๋ฐฐ์› ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,58 @@ +package christmas.domain.type; + +public enum Menu { + //์—ํ”ผํƒ€์ด์ € + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, Category.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, Category.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, Category.APPETIZER), + + //๋ฉ”์ธ + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, Category.MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, Category.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, Category.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, Category.MAIN), + + //๋””์ €ํŠธ + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, Category.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, Category.DESSERT), + + //์Œ๋ฃŒ + ZERO_COKE("์ œ๋กœ์ฝœ๋ผ", 3_000, Category.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, Category.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, Category.BEVERAGE); + + private final String name; + private final int price; + private final Category category; + + Menu(String name, int price, Category category) { + this.name = name; + this.price = price; + this.category = category; + } + + public static Menu findByName(String menuName) { + for (Menu menu : Menu.values()) { + if (menu.getName().equals(menuName)) { + return menu; + } + } + return null; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public Category getCategory() { + return category; + } + + public enum Category { + APPETIZER, MAIN, DESSERT, BEVERAGE + } +}
Java
์ฑ…์ž„์„ ๋ถ„๋ฆฌํ•˜๋ ค๊ณ  ๊ทธ๋ ‡๊ฒŒ ์ž‘์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ฐ”๋กœ ๋ฉ”๋‰ด์—์„œ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋ฉด ์ถ”์ ํ•˜๊ธฐ ์‰ฌ์šธ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”
@@ -0,0 +1,41 @@ +package christmas.domain.model; + +import christmas.domain.type.Menu; + +import java.util.Map; + +public class OrderInfo { + private final int date; + private final Map<Menu, Integer> order; + private final int totalOrderPrice; + + public OrderInfo(int date, Map<Menu, Integer> order) { + this.date = date; + this.order = order; + this.totalOrderPrice = calculateTotalOrderPrice(); + } + + public int getDate() { + return date; + } + public Map<Menu, Integer> getOrder() { + return order; + } + + public int getTotalOrderPrice() { + return totalOrderPrice; + } + + private int calculateTotalOrderPrice() { + int totalOrderPrice = 0; + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalOrderPrice += menu.getPrice() * quantity; + } + + return totalOrderPrice; + } +}
Java
date์— ๋Œ€ํ•œ validation์„ InputView์—์„œ ์ง„ํ–‰ํ•˜์…จ๊ตฐ์š”! ์ €๋„ ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ ์–ด๋–ค ๊ฒƒ์ด ๋” ํšจ์œจ์ ์ผ๊นŒ ๊ณ ๋ฏผ์„ ๋งŽ์ด ํ•ด๋ดค๋Š”๋ฐ @T3rryAhn ๋‹˜์˜ ์ƒ๊ฐ์€ ์–ด๋–ค ์ง€ ์—ฌ์ญ™๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค. ์ €๋„ ์ฒ˜์Œ์—๋Š” ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•œ validation์„ InputView์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„์ง€ domain์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ์ง€ ๊ณ ๋ฏผ์„ ๋งŽ์ด ํ–ˆ์—ˆ๋Š”๋ฐ์š”. ํ”„๋กœ๊ทธ๋žจ์ด ๋ณต์žกํ•ด์งˆ ์ˆ˜๋ก InputView๊ฐ€ ๊ฒ€์ฆํ•ด์•ผํ•  validation์˜ ์ข…๋ฅ˜๊ฐ€ ๋งŽ์•„์ง์œผ๋กœ ์ €๋Š” validation์„ domain์œผ๋กœ ์ฑ…์ž„์„ ๋„˜๊ธฐ๋Š” ๊ฒƒ์ด ๋” ์ข‹๋‹ค๊ณ  ํŒ๋‹จํ–ˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์ €๋Š” InputView์—์„œ validation์€ ์ตœ์†Œํ•œ์˜ ์ž…๋ ฅ ์˜ค๋ฅ˜(Ex. `NumberFormatException`, ๋นˆ ์ž…๋ ฅ๊ฐ’, ๊ธ€์ž์ˆ˜ ์ œํ•œ ๋“ฑ)๋งŒ ๊ฒ€์ฆํ•˜๊ณ , ์ž…๋ ฅ์ด domain ๊ด€๋ จ ๊ฐ’์œผ๋กœ ์œ ํšจํ•œ ์ง€ ํŒ๋‹จํ•˜๋Š” ๊ฑด, ๋ชจ๋ธ ๊ฐ์ฒด ์Šค์Šค๋กœ๊ฐ€ ์ž์‹ ์˜ ๊ฐ’์„ ๊ฒ€์ฆํ•˜๋„๋ก ๊ตฌ์กฐ๋ฅผ ์„ธ์› ์Šต๋‹ˆ๋‹ค. @T3rryAhn ๋‹˜์˜ ์ƒ๊ฐ์€ ์–ด๋– ์‹ ๊ฐ€์š”? ์ฐธ๊ณ  : https://tecoble.techcourse.co.kr/post/2020-05-29-wrap-primitive-type/
@@ -0,0 +1,41 @@ +package christmas.domain.model; + +import christmas.domain.type.Menu; + +import java.util.Map; + +public class OrderInfo { + private final int date; + private final Map<Menu, Integer> order; + private final int totalOrderPrice; + + public OrderInfo(int date, Map<Menu, Integer> order) { + this.date = date; + this.order = order; + this.totalOrderPrice = calculateTotalOrderPrice(); + } + + public int getDate() { + return date; + } + public Map<Menu, Integer> getOrder() { + return order; + } + + public int getTotalOrderPrice() { + return totalOrderPrice; + } + + private int calculateTotalOrderPrice() { + int totalOrderPrice = 0; + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalOrderPrice += menu.getPrice() * quantity; + } + + return totalOrderPrice; + } +}
Java
Map<Menu, Integer>์˜ ๊ฒฝ์šฐ ์ปฌ๋ ‰์…˜์— ํ•ด๋‹นํ•ฉ๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ ์ผ๊ธ‰ ์ปฌ๋ ‰์…˜์„ ์‚ฌ์šฉํ•ด์„œ ๊ด€๋ฆฌํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”? ์ฐธ๊ณ  : https://tecoble.techcourse.co.kr/post/2020-05-08-First-Class-Collection/
@@ -0,0 +1,41 @@ +package christmas.domain.model; + +import christmas.domain.type.Menu; + +import java.util.Map; + +public class OrderInfo { + private final int date; + private final Map<Menu, Integer> order; + private final int totalOrderPrice; + + public OrderInfo(int date, Map<Menu, Integer> order) { + this.date = date; + this.order = order; + this.totalOrderPrice = calculateTotalOrderPrice(); + } + + public int getDate() { + return date; + } + public Map<Menu, Integer> getOrder() { + return order; + } + + public int getTotalOrderPrice() { + return totalOrderPrice; + } + + private int calculateTotalOrderPrice() { + int totalOrderPrice = 0; + + for (Map.Entry<Menu, Integer> entry : order.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + totalOrderPrice += menu.getPrice() * quantity; + } + + return totalOrderPrice; + } +}
Java
3์ฃผ์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์—์„œ '**๊ฐ์ฒด๋Š” ๊ฐ์ฒด๋‹ต๊ฒŒ **'๋ผ๋Š” ๊ฒƒ์ด ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ `private final Map<Menu, Integer> order;`์œผ๋กœ ์„ ์–ธํ•œ order์„ ๋ฐ˜ํ™˜ํ•˜๋Š”๋ฐ์š”. Map<Menu, Integer>์€ ์ปฌ๋ ‰์…˜ ์ค‘์— ํ•˜๋‚˜์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ final ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ํ•ด๋„ ๊ฐ’์˜ ๋ณ€๊ฒฝ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค ใ… ใ…กใ… . ๋”ฐ๋ผ์„œ ์ปฌ๋ ‰์…˜ ๋ณ€์ˆ˜๋Š” ์ตœ๋Œ€ํ•œ getter ์‚ฌ์šฉ์„ ์ง€์–‘ํ•˜๊ณ  ๊ฐ์ฒด์— ๋ฉ”์‹œ์ง€๋ฅผ ๋˜์ง€๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋ฉด ์ข‹์€๋ฐ์š”. ์œ„์˜ comment์™€ ์—ฐ๊ด€ํ•˜์—ฌ '์ผ๊ธ‰์ปฌ๋ ‰์…˜' ๊ฐœ๋…์ด ๋งŽ์ด ๋„์›€ ๋˜์‹ค ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ฐธ๊ณ  : https://tecoble.techcourse.co.kr/post/2020-05-08-First-Class-Collection/
@@ -0,0 +1,112 @@ +package christmas.view; + +import christmas.domain.model.DecemberEvent; +import christmas.domain.model.EventResult; +import christmas.domain.type.Badge; +import christmas.domain.type.Benefit; +import christmas.domain.type.Menu; +import christmas.util.MapToStringConverter; + +import java.util.Map; + +public class OutputView { + private static final String LINE_SEPARATOR = System.lineSeparator(); + private static final String INTRO_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค."; + private static final String RESULT_INTRO_MESSAGE = "12์›” %d์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"; + private static final String EVENT_CAUTION = "์ด๋ฒคํŠธ ์ฃผ์˜ ์‚ฌํ•ญ!" + LINE_SEPARATOR + + " - ์ด์ฃผ๋ฌธ ๊ธˆ์•ก 10,000์› ์ด์ƒ๋ถ€ํ„ฐ ์ด๋ฒคํŠธ๊ฐ€ ์ ์šฉ๋ฉ๋‹ˆ๋‹ค." + LINE_SEPARATOR + + " - ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธ ์‹œ, ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค." + LINE_SEPARATOR + + " - ๋ฉ”๋‰ด๋Š” ํ•œ๋ฒˆ์— ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค." + LINE_SEPARATOR; + private static final String RESULT_HEAD_ORDERED_MENU = "<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"; + private static final String RESULT_HEAD_TOTAL_PRICE = "<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"; + private static final String RESULT_HEAD_GIVEAWAY_MENU = "<์ฆ์ • ๋ฉ”๋‰ด>"; + private static final String RESULT_HEAD_BENEFIT_DETAILS = "<ํ˜œํƒ ๋‚ด์—ญ>"; + private static final String RESULT_HEAD_TOTAL_BENEFIT_PRICE = "<์ดํ˜œํƒ ๊ธˆ์•ก>"; + private static final String RESULT_HEAD_DISCOUNTED_TOTAL_PRICE = "<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"; + private static final String RESULT_HEAD_BADGE = "<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"; + private static final String PRICE = "%,d์›"; + private static final String NONE = "์—†์Œ"; + + public void printIntro() { + System.out.printf(INTRO_MESSAGE + LINE_SEPARATOR); + } + + public void printCaution() { + System.out.printf(EVENT_CAUTION + LINE_SEPARATOR); + } + + public void printResult(EventResult eventResult) { + printResultIntro(eventResult.getOrder().getDate()); + printOrder(eventResult.getOrder().getOrder()); + printTotalPrice(eventResult.getOrder().getTotalOrderPrice()); + printGiveawayMenu(eventResult.hasGiveawayBenefits()); + printBenefitDetails(eventResult.getBenefitHistory()); + printTotalBenefitPrice(eventResult.getTotalBenefitsPrice()); + printDiscountedPrice(eventResult.getFinalPrice()); + printBadge(eventResult.getBadge()); + } + + public void printResultIntro(int date) { + System.out.printf(LINE_SEPARATOR + RESULT_INTRO_MESSAGE + LINE_SEPARATOR, date); + } + + public void printOrder(Map<Menu, Integer> order) { + System.out.printf(LINE_SEPARATOR + RESULT_HEAD_ORDERED_MENU + LINE_SEPARATOR); + String result = MapToStringConverter.orderToString(order); + System.out.printf(result); + } + + + + public void printTotalPrice(int totalOrderPrice) { + System.out.printf(LINE_SEPARATOR + RESULT_HEAD_TOTAL_PRICE + LINE_SEPARATOR); + + int price = totalOrderPrice; + System.out.printf(PRICE, price); + System.out.println(); + } + + public void printGiveawayMenu(boolean hasGiveawayBenefits) { + System.out.printf(LINE_SEPARATOR + RESULT_HEAD_GIVEAWAY_MENU + LINE_SEPARATOR); + + String result = NONE + LINE_SEPARATOR; + + if (hasGiveawayBenefits) { + result = MapToStringConverter.orderToString(DecemberEvent.getGiveawayBenefits()); + } + + System.out.printf(result); + } + + public void printBenefitDetails(Map<Benefit, Integer> benefitAndPrice) { + System.out.printf(LINE_SEPARATOR + RESULT_HEAD_BENEFIT_DETAILS + LINE_SEPARATOR); + String result = NONE + LINE_SEPARATOR; + + if (!benefitAndPrice.isEmpty()) { + result = MapToStringConverter.benefitToString(benefitAndPrice); + } + + System.out.printf(result); + } + + public void printTotalBenefitPrice(int totalBenefitPrice) { + System.out.printf(LINE_SEPARATOR + RESULT_HEAD_TOTAL_BENEFIT_PRICE + LINE_SEPARATOR); + String result = "-" + PRICE + LINE_SEPARATOR; + if (totalBenefitPrice == 0) { + result = PRICE + "\n"; + } + System.out.printf(result, totalBenefitPrice); + } + + public void printDiscountedPrice(int finalPrice) { + System.out.printf(LINE_SEPARATOR + RESULT_HEAD_DISCOUNTED_TOTAL_PRICE + LINE_SEPARATOR); + + System.out.printf(PRICE + LINE_SEPARATOR, finalPrice); + } + + public void printBadge(Badge badge) { + System.out.printf(LINE_SEPARATOR + RESULT_HEAD_BADGE + LINE_SEPARATOR); + + System.out.printf(badge.getName() + LINE_SEPARATOR); + } +}
Java
OutputView์—์„œ ์‚ฌ์šฉ๋˜๋Š” ์ƒ์ˆ˜๊ฐ’ ๊ฒฝ์šฐ, enum์œผ๋กœ ๋ฌถ์–ด์„œ ๊ด€๋ฆฌํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ํ›จ์”ฌ ๊น”๋”ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,173 @@ +์ž‘์„ฑ์ž: ์•ˆํƒœ๋ฆฌ + +# ๐ŸŽ…ํฌ๋ฆฌ์Šค๋งˆ์Šค ํ”„๋กœ๋ชจ์…˜ + +**์ด๋ฒคํŠธ ๋ชฉํ‘œ** +```` +1. ์ค‘๋ณต๋œ ํ• ์ธ๊ณผ ์ฆ์ •์„ ํ—ˆ์šฉํ•ด์„œ, ๊ณ ๊ฐ๋“ค์ด ํ˜œํƒ์„ ๋งŽ์ด ๋ฐ›๋Š”๋‹ค๋Š” ๊ฒƒ์„ ์ฒด๊ฐํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š” ๊ฒƒ +2. ์˜ฌํ•ด 12์›”์— ์ง€๋‚œ 5๋…„ ์ค‘ ์ตœ๊ณ ์˜ ํŒ๋งค ๊ธˆ์•ก์„ ๋‹ฌ์„ฑ +3. 12์›” ์ด๋ฒคํŠธ ์ฐธ์—ฌ ๊ณ ๊ฐ์˜ 5%๊ฐ€ ๋‚ด๋…„ 1์›” ์ƒˆํ•ด ์ด๋ฒคํŠธ์— ์žฌ์ฐธ์—ฌํ•˜๋Š” ๊ฒƒ +```` + +--------------- +## โš™ ๊ธฐ๋Šฅ ๋ชฉ๋ก + +### ์‚ฌ์šฉ์ž ์ธํ„ฐํŽ˜์ด์Šค + - ์‚ฌ์šฉ์ž์—๊ฒŒ ์ž…๋ ฅ์„ ์š”์ฒญํ•˜๋Š” ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ + - ์‚ฌ์šฉ์ž ์ž…๋ ฅ ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ, '[ERROR]'๋กœ ์‹œ์ž‘ํ•˜๋Š” ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ +### ๋‚ ์งœ ์ž…๋ ฅ ๋ฐ ๊ฒ€์ฆ + - ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ 12์›” ์ค‘ ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋ฅผ ์ˆซ์ž๋กœ ์ž…๋ ฅ๋ฐ›์Œ + - ์ž…๋ ฅ๋ฐ›์€ ๋‚ ์งœ๊ฐ€ 1 ์ด์ƒ 31 ์ดํ•˜์ธ์ง€ ๊ฒ€์ฆ + - ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ ์ž…๋ ฅ ์‹œ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ „๋‹ฌ ๋ฐ ์žฌ์ž…๋ ฅ ์š”์ฒญ +### ๋ฉ”๋‰ด ์ฃผ๋ฌธ ์ž…๋ ฅ ๋ฐ ๊ฒ€์ฆ + - ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ฃผ๋ฌธํ•  ๋ฉ”๋‰ด์™€ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅ๋ฐ›์Œ (์˜ˆ: ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2, ๋ ˆ๋“œ์™€์ธ-1) + - ์ž…๋ ฅ๋ฐ›์€ ๋ฉ”๋‰ด๊ฐ€ ๋ฉ”๋‰ดํŒ์— ์žˆ๋Š”์ง€, ์ˆ˜๋Ÿ‰์ด ์œ ํšจํ•œ์ง€ ์ฃผ๋ฌธ ๊ฒ€์ฆ + - ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ ์ž…๋ ฅ ์‹œ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ „๋‹ฌ ๋ฐ ์žฌ์ž…๋ ฅ ์š”์ฒญ +### ํ• ์ธ ๋ฐ ์ฆ์ • ์ด๋ฒคํŠธ ๊ณ„์‚ฐ + - ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ ๊ณ„์‚ฐ + - ํ‰์ผ ํ• ์ธ ๊ณ„์‚ฐ (๋””์ €ํŠธ ๋ฉ”๋‰ด) + - ์ฃผ๋ง ํ• ์ธ ๊ณ„์‚ฐ (๋ฉ”์ธ ๋ฉ”๋‰ด) + - ํŠน๋ณ„ ํ• ์ธ ๊ณ„์‚ฐ (๋‹ฌ๋ ฅ์— ๋ณ„ ํ‘œ์‹œ๋œ ๋‚ ) + - ์ฆ์ • ์ด๋ฒคํŠธ ์ ์šฉ (์ด์ฃผ๋ฌธ ๊ธˆ์•ก์ด 12๋งŒ ์› ์ด์ƒ์ผ ๊ฒฝ์šฐ ์ƒดํŽ˜์ธ ์ฆ์ •) +### ํ˜œํƒ ๋‚ด์—ญ ๋ฐ ์ดํ˜œํƒ ๊ธˆ์•ก ๊ณ„์‚ฐ + - ํ• ์ธ ๊ธˆ์•ก์˜ ํ•ฉ๊ณ„ ๊ณ„์‚ฐ + - ์ฆ์ • ๋ฉ”๋‰ด ๊ฐ€๊ฒฉ ๊ณ„์‚ฐ + - ์ดํ˜œํƒ ๊ธˆ์•ก ๊ณ„์‚ฐ +### ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก ๊ณ„์‚ฐ + - ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก ๊ณ„์‚ฐ +### ์ด๋ฒคํŠธ ๋ฐฐ์ง€ ๋ถ€์—ฌ + - ์ดํ˜œํƒ ๊ธˆ์•ก์— ๋”ฐ๋ฅธ ์ด๋ฒคํŠธ ๋ฐฐ์ง€ ๋ถ€์—ฌ (๋ณ„, ํŠธ๋ฆฌ, ์‚ฐํƒ€) +### ๊ฒฐ๊ณผ ์ถœ๋ ฅ + - ์ฃผ๋ฌธ ๋ฉ”๋‰ด, ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก, ์ฆ์ • ๋ฉ”๋‰ด, ํ˜œํƒ ๋‚ด์—ญ, ์ดํ˜œํƒ ๊ธˆ์•ก, ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก, ์ด๋ฒคํŠธ ๋ฐฐ์ง€๋ฅผ ์ถœ๋ ฅ +### ๋‹จ์œ„ ํ…Œ์ŠคํŠธ + - ๊ฐ ๊ธฐ๋Šฅ๋ณ„๋กœ JUnit 5์™€ AssertJ๋ฅผ ์ด์šฉํ•˜์—ฌ ๋‹จ์œ„ ํ…Œ์ŠคํŠธ ์ž‘์„ฑ + +------------ + +## ํฌ๋ฆฌ์Šค๋งˆ์Šค ํ”„๋กœ๋ชจ์…˜ ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ + +``` +๐Ÿ”ป๐Ÿ“main + ๐Ÿ”ป๐Ÿ“java + ๐Ÿ”ป๐Ÿ“christmas + ๐Ÿ”ป๐Ÿ“controller + EventPlanner.java + ๐Ÿ”ป๐Ÿ“domain + ๐Ÿ”ป๐Ÿ“logic + ChristmasEventCalculator.java + EventCalculator.java + EventService.java + ๐Ÿ”ป๐Ÿ“model + DecemberEvent.java + EventResult.java + OrderInfo.java + ๐Ÿ”ป๐Ÿ“type + Badge.java (enum) + Benefit.java (enum) + Menu.java (enum) + ๐Ÿ”ป๐Ÿ“view + InputView.java + OutputView.java + ๐Ÿ”ป๐Ÿ“util + DateValidator.java + MapToStringConverter.java + OrderValidator.java + StringUtil.java + ValidationException.java + Application.java +``` +### ์„ค๋ช… +#### controller +> ์‚ฌ์šฉ์ž์˜ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๊ณ , ๋ชจ๋ธ์„ ์กฐ์ž‘, ์ ์ ˆํ•œ ์‘๋‹ต์„ ๋ทฐ์— ์ „๋‹ฌํ•˜๋Š” ํด๋ž˜์Šค๊ฐ€ ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค. + +#### domain +> ๋„๋ฉ”์ธ ๋กœ์ง์„ ๋‹ด๋‹นํ•˜๋Š” ํด๋ž˜์Šค๋“ค์ด ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค. <br> + +- #### logic +> **EventCalculator**: ์ด๋ฒคํŠธ ํ• ์ธ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. <br> +> **ChristmasEventCalculator**: ๋‚ ์งœ ๊ธฐ๋ฐ˜ ํ• ์ธ ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. <br> +> **EventService**: ์ฃผ๋ฌธ ์ •๋ณด๋กœ ์ด๋ฒคํŠธ ๊ฒฐ๊ณผ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๋Š” ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค. <br> + +- #### model +> **DecemberEvent**: ์ด๋ฒคํŠธ ๊ด€๋ จ ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. <br> +> **EventResult**: ์ด๋ฒคํŠธ ๊ฒฐ๊ณผ๋ฅผ ๋‹ด๋Š” ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค. <br> +> **OrderInfo**: ์ฃผ๋ฌธ ์ •๋ณด๋ฅผ ๋‹ด๋Š” ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค. <br> + +- #### type +> **Benefit**: ํ˜œํƒ ์ข…๋ฅ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์—ด๊ฑฐํ˜•์ž…๋‹ˆ๋‹ค. <br> +> **Menu**: ๋ฉ”๋‰ด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์—ด๊ฑฐํ˜•์ž…๋‹ˆ๋‹ค. <br> +> **Badge**: ๋ฑƒ์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์—ด๊ฑฐํ˜•์ž…๋‹ˆ๋‹ค. <br> + + +#### view +> ์‚ฌ์šฉ์ž ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ํด๋ž˜์Šค๋“ค์ด ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค. <br> +> +> **InputView**: ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ์ฒ˜๋ฆฌ. <br> +> **OutputView**: ๊ฒฐ๊ณผ ์ถœ๋ ฅ์„ ์ฒ˜๋ฆฌ. <br> + +#### util +> ์œ ํ‹ธ๋ฆฌํ‹ฐ ํด๋ž˜์Šค๋“ค์ด ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค. <br> +> +> **DateValidator**: ๋‚ ์งœ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๋กœ์ง์„ ํฌํ•จ. <br> +> **MapToStringConverter**: Map์˜ key, value ๊ฐ’์„ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ์ž‘์—…์ฒ˜๋ฆฌ. <br> +> **OrderValidator**: ๋ฉ”๋‰ด์™€ ์ˆ˜๋Ÿ‰ ์ž…๋ ฅ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๋กœ์ง์„ ํฌํ•จ. <br> +> **StringUtil**: ๋ฌธ์ž์—ด์— ํƒ€ํ‚ท ๋ฌธ์ž๊ฐ€ ๋ช‡๊ฐœ์žˆ๋Š”์ง€ ์นด์šดํŠธํ•˜๋Š” ๊ธฐ๋Šฅ. <br> +> **ValidationException**: ์‚ฌ์šฉ์ž ์ •์˜ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ํด๋ž˜์Šค. <br> + +---------------------- +## ๋™์ž‘ +```` +1. Applicaton ์—์„œ InputView, OutputView ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  EventPlaner(inputView, outputView)์— ์ฃผ์ž…์‹œ์ผœ EventPlanner๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. +2. EventPlanner์—์„œ InputView๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉ์ž์—๊ฒŒ ๋‚ ์งœ(int date)์™€ ์ฃผ๋ฌธ(Map<๋ฉ”๋‰ด, ์ˆ˜๋Ÿ‰>)์„ ๊ฒ€์ฆํ›„ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. +3. EventService(๋‚ ์งœ, ์ฃผ๋ฌธ)์„ ์ฃผ์ž…ํ•ด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. eventService(๊ฐ์ฒด)๊ฐœ ์ƒ์„ฑ๋จ๊ณผ ๋™์‹œ์— orderInfo(๊ฐ์ฒด)๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค. +4. orderInfo๋Š” ์Šค์Šค๋กœ ์ฃผ๋ฌธ ์ด์•ก์„ ๊ณ„์‚ฐํ•ด์„œ ์ƒ์„ฑ๋œ๋‹ค. orderInfo์˜ ์ •๋ณด๋ฅผ ์‚ฌ์šฉํ•ด + eventService์—์„œ ๋กœ์ง์˜ ๊ณ„์‚ฐ๊ธฐ(EventCalculator, ChristmasEventCalculator) ํด๋ž˜์Šค๋“ค์„ ํ™œ์šฉํ•ด ํ• ์ธ ํ˜œํƒ์„ ๊ณ„์‚ฐํ•œ๋‹ค. +5. ๊ณ„์‚ฐ๊ธฐ๋“ค์€ DecemberEvent์—๊ฒŒ ํ• ์ธ ์—ฌ๋ถ€๋ฅผ ๋ฌป๋Š”๋‹ค. +6. eventService์—์„œ ๊ณ„์‚ฐ๋œ ๊ฐ’๋“ค๋กœ eventResult๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. +7. eventResult์˜ ๊ฐ’๋“ค์„ outView์—์„œ ์ถœ๋ ฅํ•œ๋‹ค. +```` + +------------------- +## ์˜ˆ์™ธ ์ƒํ™ฉ + +๋‚ ์งœ ์ž…๋ ฅ +- ๋ฌธ์ž์—ด ์ž…๋ ฅ, ๊ณต๋ฐฑ ์ž…๋ ฅ + +์ฃผ๋ฌธ ์ž…๋ ฅ +- **case 1: ๊ณต๋ฐฑ๋งŒ์„ ์ œ์™ธํ•œ ์ž˜๋ชป๋œ ์ž…๋ ฅ์„ ๋ฐ›์•˜๋‹ค๋ฉด ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ†ต๊ณผ ์‹œํ‚ฌ ๊ฒƒ์ธ๊ฐ€?** +```` +์ž…๋ ฅ ์˜ˆ์‹œ: ํƒ€ํŒŒ์Šค -1, ์ œ๋กœ ์ฝœ๋ผ-1,์ดˆ์ฝ” ์ผ€์ดํฌ- 3 + +์‚ฌ์šฉ์ž ์นœํ™”์  ๋ฐฉ์•ˆ: ๊ณต๋ฐฑ ์ œ๊ฑฐ ๊ธฐ๋Šฅ์„ ์ด์šฉํ•˜๋ฉด ๋˜๋ฏ€๋กœ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ†ต๊ณผ์‹œํ‚จ๋‹ค. +ํ•˜์ง€๋งŒ, ๋ฐ์ดํ„ฐ์˜ ์ผ๊ด€์„ฑ ์œ ์ง€ํ•˜๊ธฐ ์–ด๋ ค์šธ ์ˆ˜ ์žˆ์Œ, ๋กœ์ง์ด ๋ณต์žกํ•ด์ ธ์„œ ์˜ค๋ฅ˜๋ฐœ์ƒ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ์Œ. +(ex. ํƒ€ ํŒŒ์Šค, ํƒ€ํŒŒ์Šค, ํƒ€ํŒŒ ์Šค)์™€ ๊ฐ™์ด ๊ณต๋ฐฑ์ด ์ œ๋Œ€๋กœ ์ œ๊ฑฐ๊ฐ€ ์•ˆ๋˜๊ฒŒ ๋กœ์ง์„ ์งฐ๋Š”์ง€ ์ž˜ ํ™•์ธํ•ด์•ผํ•จ. +๊ฒฐ๋ก : ํ”„๋ก ํŠธ์—์„œ ๊ณต๋ฐฑ์—ฌ๋ถ€๋ฅผ ์ž˜ ๊ฐ€๊ณตํ•ด์„œ ์ „๋‹ฌ๋ฐ›์•„ ๋ฐฑ์—”๋“œ์—์„œ๋Š” ์ •ํ™•ํ•œ ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›๋„๋ก ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒํ•˜๋Š” ๊ฒƒ์ด ๋งž๋Š”๊ฒƒ ๊ฐ™๋‹ค. +```` + +- ์ค‘๋ณต๋œ ๋ฉ”๋‰ด๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. +- ์—†๋Š” ๋ฉ”๋‰ด๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. + +**case 2** +- ์ฃผ๋ฌธ ์ž…๋ ฅ: ์ƒดํŽ˜์ธ-1-1, ์ดˆ์ฝ”์ผ€์ดํฌ-1 ์„ ํ†ต๊ณผํ•ด์„œ ๋ฐ›์Œ. +- ์ฃผ๋ฌธ ์ž…๋ ฅ: ๋ฉ”๋‰ด -- ์ž…๋ ฅ์‹œ ์˜ค๋ฅ˜๋ฐœ์ƒ. +> ',' ๋กœ ๋ถ„๋ฆฌํ•œ ๋ฌธ์ž์—ด์— '-' ๊ฐฏ์ˆ˜๊ฐ€ 1๊ฐœ ๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ์˜ˆ์™ธ์ฒ˜๋ฆฌ. + + +-------- +## ๋ฆฌํŽ™ํ† ๋ง ํ• ๋ฒ•ํ•œ ๊ฒƒ๋“ค + +util์— MapReader ํด๋ž˜์Šค ๋งŒ๋“ค๊ธฐ +``` +private void readMenuAndQuantity(Map<Menu, Integer> menuAndQuantity) { + for (Map.Entry<Menu, Integer> entry : menuAndQuantity.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + + //์—ฐ์‚ฐ ๋ช…๋ น + } + +} +``` +์ด์œ : ์œ„์™€ ๊ฐ™์€ ํ˜•ํƒœ๊ฐ€ ๋งŽ์ด ๋ฐ˜๋ณตํ•ด์„œ ์“ฐ์ด๊ณ  ์žˆ์Œ. + +//์—ฐ์‚ฐ ๋ช…๋ น ๋ถ€๋ถ„๋งŒ ๊ฐˆ์•„๋ผ์šฐ๋Š” ๋ฐฉ๋ฒ•์ด ์—†์„๊นŒ? > BiConsumer ์•Œ์•„๋ณด๊ธฐ.
Unknown
README ๊น”๋”ํ•ด์„œ ์ •๋ฆฌ๊ฐ€ ์ž˜ ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,116 @@ +package christmas.domain.logic; + +import christmas.domain.model.DecemberEvent; +import christmas.domain.model.OrderInfo; +import christmas.domain.model.EventResult; +import christmas.domain.type.Badge; +import christmas.domain.type.Benefit; +import christmas.domain.type.Menu; + +import java.util.HashMap; +import java.util.Map; + +public class EventService { + private final OrderInfo orderInfo; + private Map<Benefit, Integer> benefitHistory = new HashMap<>(); + + public EventService(int date, Map<Menu, Integer> order) { + this.orderInfo = new OrderInfo(date, order); + } + + public EventResult makeEventResult() { + int totalOrderPrice = orderInfo.getTotalOrderPrice(); + int date = orderInfo.getDate(); + int totalBenefitsPrice = 0; + Badge badge = Badge.NONE; + + if (EventCalculator.isEligibleForEvent(totalOrderPrice)) { + checkAll(totalOrderPrice, date); + totalBenefitsPrice = calculateTotalBenefitsPrice(); + badge = checkBadge(totalBenefitsPrice); + } + + EventResult eventResult = new EventResult(orderInfo, benefitHistory, totalBenefitsPrice, badge); + return eventResult; + } + + private void checkAll(int totalOrderPrice, int date) { + checkChristmasEvent(date); + checkWeekdayDiscount(date); + checkWeekendDiscount(date); + checkSpecialDiscount(date); + checkGiveaway(totalOrderPrice); + } + + private void updateBenefitHistory(Benefit benefit, int discount) { + if (discount != 0) { + benefitHistory.put(benefit, discount); + } + } + + private void checkGiveaway(int totalPrice) { + Map<Menu, Integer> giveaway = EventCalculator.calculateGiveawayEvent(totalPrice); + int discount = 0; + + for (Map.Entry<Menu, Integer> entry : giveaway.entrySet()) { + Menu menu = entry.getKey(); + int quantity = entry.getValue(); + int menuPrice = menu.getPrice(); + + discount += menuPrice * quantity; + } + + if (discount != 0) { + updateBenefitHistory(Benefit.GIVEAWAY, discount); + } + } + + private void checkWeekdayDiscount(int date) { + int discount = 0; + + if (!DecemberEvent.isWeekend(date)) { + discount = EventCalculator.calculateWeekdayDiscount(date, orderInfo.getOrder()); + updateBenefitHistory(Benefit.WEEKDAY, discount); + } + } + + private void checkWeekendDiscount(int date) { + int discount = 0; + + if (DecemberEvent.isWeekend(date)) { + discount = EventCalculator.calculateWeekendDiscount(date, orderInfo.getOrder()); + updateBenefitHistory(Benefit.WEEKEND, discount); + } + } + + private void checkChristmasEvent(int date) { + int discount = ChristmasEventCalculator.calculateChristmasDiscount(date); + + if (discount != 0) { + updateBenefitHistory(Benefit.CHRISTMAS_D_DAY, discount); + } + } + + private void checkSpecialDiscount(int date) { + int discount = EventCalculator.calculateSpecialDiscount(date); + + if (discount != 0) { + updateBenefitHistory(Benefit.SPECIAL, discount); + } + } + + private int calculateTotalBenefitsPrice() { + int totalBenefitsPrice = benefitHistory + .values() + .stream() + .mapToInt(Integer::intValue) + .sum(); + + return totalBenefitsPrice; + } + + private Badge checkBadge(int totalBenefitsPrice) { + return EventCalculator.calculateBadge(totalBenefitsPrice); + } +} +
Java
EventService๋ผ๋Š” ๊ฐ์ฒด์˜ ์กด์žฌ ์ด์œ ๊ฐ€ ์ž˜ ์™€๋‹ฟ์ง€ ์•Š๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค ๊ฐ์ฒด์ธ์ง€, ์œ ํ‹ธ์šฉ ๊ฐ์ฒด์ธ์ง€, ํ˜น์€ ๋„๋ฉ”์ธ ๊ฐ์ฒด์ธ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค ๊ฐ์ฒด๋ผ๋ฉด logic์ด๋ผ๋Š” ํŒจํ‚ค์ง€๋ช…์ด ๋ชจํ˜ธํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•˜๊ณ , service ํŒจํ‚ค์ง€๋ฅผ ๋งŒ๋“ค์–ด ๊ทธ ํ•˜์— ์žˆ์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,82 @@ +package christmas.controller; + +import static christmas.domain.event.EventConstants.*; + +import christmas.domain.restaurant.Orders; +import christmas.domain.restaurant.VisitDate; +import christmas.service.RestaurantCalculator; +import christmas.view.inputview.InputValueType; +import christmas.view.inputview.InputView; +import christmas.view.outputview.OutputView; + +public class WootecoRestaurantController { + private final RestaurantCalculator restaurantCalculator; + private final EventPlanerController eventPlanerController; + + public WootecoRestaurantController(RestaurantCalculator restaurantCalculator, + EventPlanerController eventPlanerController) { + this.restaurantCalculator = restaurantCalculator; + this.eventPlanerController = eventPlanerController; + } + + public void takeReservation() { + VisitDate visitDate = getVisitDate(); + Orders orders = getOrders(); + int orderTotalAmount = getOrderTotalAmount(orders); + + showEventPreviewMessage(visitDate); + showOrderDetails(orders, orderTotalAmount); + executeEvent(visitDate, orders, orderTotalAmount); + } + + private VisitDate getVisitDate() { + OutputView.printHelloMessage(); + VisitDate visitDate = inputVisitDate(); + return visitDate; + } + + private Orders getOrders() { + OutputView.printMenu(); + Orders orders = inputOrders(); + return orders; + } + + private int getOrderTotalAmount(Orders orders) { + return restaurantCalculator.getOrderTotalAmount(orders); + } + + private static void showEventPreviewMessage(VisitDate visitDate) { + OutputView.printEventPreviewMessage(visitDate); + } + + private static void showOrderDetails(Orders orders, int orderTotalAmount) { + OutputView.printOrder(orders, orderTotalAmount); + } + + private void executeEvent(VisitDate visitDate, Orders orders, int orderTotalAmount) { + if (canApplyEvent(orderTotalAmount)) { + eventPlanerController.executeEventPlaner(visitDate, orders, orderTotalAmount); + } + } + + private boolean canApplyEvent(int orderTotalAmount) { + if (isOrderTotalAmountValidForEvent(orderTotalAmount)) { + return true; + } + + eventPlanerController.notApplyEvent(orderTotalAmount); + return false; + } + + private static boolean isOrderTotalAmountValidForEvent(int orderTotalAmount) { + return orderTotalAmount >= EVENT_MIN_PAY_AMOUNT.getValue(); + } + + private Orders inputOrders() { + return (Orders) InputView.inputValue(InputValueType.ORDERS); + } + + private VisitDate inputVisitDate() { + return (VisitDate) InputView.inputValue(InputValueType.VISIT_DATE); + } +}
Java
๊ฐœ์ธ์ ์ธ ์ƒ๊ฐ์œผ๋กœ, ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ ๋‹ค๋ฅธ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜๋กœ ๊ฐ€์ง€๊ณ  ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์ด ๋งž๋Š”์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๊ณตํ†ต๋œ ๋ถ€๋ถ„์ด ์žˆ์–ด์„œ๋ผ๋ฉด, ์„œ๋น„์Šค๋ฅผ ๋”ฐ๋กœ ๋‘๊ฑฐ๋‚˜ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ํ•˜๋‚˜๋กœ ํ•ฉ์น˜๋Š”๊ฑธ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,78 @@ +package christmas.domain.restaurant; + +import christmas.domain.food.Dessert; +import christmas.domain.food.Food; +import christmas.domain.food.MainFood; +import christmas.util.parser.Parser; +import christmas.util.validator.OrderValidator; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public class Orders { + private final Map<Food, Integer> orders; + + private Orders(String orders) { + validate(orders); + this.orders = registerOrders(orders); + } + + public static Orders create(String orders) { + return new Orders(orders); + } + + public int getMainMenuCount() { + int mainMenuCount = 0; + + for (Entry<Food, Integer> entry : orders.entrySet()) { + Food menu = entry.getKey(); + int menuCount = entry.getValue(); + + if (menu instanceof MainFood) { + mainMenuCount += menuCount; + } + } + + return mainMenuCount; + } + + public int getDessertMenuCount() { + int dessertMenuCount = 0; + + for (Entry<Food, Integer> entry : orders.entrySet()) { + Food menu = entry.getKey(); + int menuCount = entry.getValue(); + + if (menu instanceof Dessert) { + dessertMenuCount += menuCount; + } + } + + return dessertMenuCount; + } + + private void validate(String orders) { + OrderValidator.validateOrders(orders); + } + + private Map<Food, Integer> registerOrders(String orders) { + List<String> menus = Parser.parseMenus(orders); + List<Integer> counts = Parser.parseMenuCounts(orders); + Map<Food, Integer> order = new HashMap<>(); + + for (int idx = 0; idx < menus.size(); idx++) { + String menuName = menus.get(idx); + Food food = Menu.getFoodByName(menuName); + int count = counts.get(idx); + + order.put(food, count); + } + return order; + } + + public Map<Food, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
Map ์ž๋ฃŒ๊ตฌ์กฐ๋Š” ์“ฐ๋‹ค๋ณด๋ฉด ์€๊ทผ ์†์ด ๋งŽ์ด ๊ฐ€๊ฒŒ๋˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค๋”๋ผ๊ตฌ์š”. ๋ฌผ๋ก  ์ž๋ฃŒ๊ตฌ์กฐ๋งˆ๋‹ค ์žฅ์ ๊ณผ ๋‹จ์ ์ด ์žˆ์ง€๋งŒ ๊ฐœ์ธ์ ์œผ๋กœ ์—ฌ๊ธฐ์„œ๋Š” Map๋ณด๋‹ค๋Š” ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ๊ฐ€์ง„ ๋ณ„๋„์˜ Order ๊ฐ์ฒด๋ฅผ ๋‘๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,82 @@ +package christmas.controller; + +import static christmas.domain.event.EventConstants.*; + +import christmas.domain.restaurant.Orders; +import christmas.domain.restaurant.VisitDate; +import christmas.service.RestaurantCalculator; +import christmas.view.inputview.InputValueType; +import christmas.view.inputview.InputView; +import christmas.view.outputview.OutputView; + +public class WootecoRestaurantController { + private final RestaurantCalculator restaurantCalculator; + private final EventPlanerController eventPlanerController; + + public WootecoRestaurantController(RestaurantCalculator restaurantCalculator, + EventPlanerController eventPlanerController) { + this.restaurantCalculator = restaurantCalculator; + this.eventPlanerController = eventPlanerController; + } + + public void takeReservation() { + VisitDate visitDate = getVisitDate(); + Orders orders = getOrders(); + int orderTotalAmount = getOrderTotalAmount(orders); + + showEventPreviewMessage(visitDate); + showOrderDetails(orders, orderTotalAmount); + executeEvent(visitDate, orders, orderTotalAmount); + } + + private VisitDate getVisitDate() { + OutputView.printHelloMessage(); + VisitDate visitDate = inputVisitDate(); + return visitDate; + } + + private Orders getOrders() { + OutputView.printMenu(); + Orders orders = inputOrders(); + return orders; + } + + private int getOrderTotalAmount(Orders orders) { + return restaurantCalculator.getOrderTotalAmount(orders); + } + + private static void showEventPreviewMessage(VisitDate visitDate) { + OutputView.printEventPreviewMessage(visitDate); + } + + private static void showOrderDetails(Orders orders, int orderTotalAmount) { + OutputView.printOrder(orders, orderTotalAmount); + } + + private void executeEvent(VisitDate visitDate, Orders orders, int orderTotalAmount) { + if (canApplyEvent(orderTotalAmount)) { + eventPlanerController.executeEventPlaner(visitDate, orders, orderTotalAmount); + } + } + + private boolean canApplyEvent(int orderTotalAmount) { + if (isOrderTotalAmountValidForEvent(orderTotalAmount)) { + return true; + } + + eventPlanerController.notApplyEvent(orderTotalAmount); + return false; + } + + private static boolean isOrderTotalAmountValidForEvent(int orderTotalAmount) { + return orderTotalAmount >= EVENT_MIN_PAY_AMOUNT.getValue(); + } + + private Orders inputOrders() { + return (Orders) InputView.inputValue(InputValueType.ORDERS); + } + + private VisitDate inputVisitDate() { + return (VisitDate) InputView.inputValue(InputValueType.VISIT_DATE); + } +}
Java
ํ•ด๋‹น ๋ถ€๋ถ„์€ ์ด๋ฒคํŠธ ๋„๋ฉ”์ธ ๊ด€๋ จ ํด๋ž˜์Šค์— ์œ„์น˜ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. ์ด๋ฒคํŠธ๋ฅผ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€์— ๋Œ€ํ•ด์„œ๋Š” ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์— ํ•ด๋‹น๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”!
@@ -0,0 +1,82 @@ +package christmas.controller; + +import static christmas.domain.event.EventConstants.*; + +import christmas.domain.restaurant.Orders; +import christmas.domain.restaurant.VisitDate; +import christmas.service.RestaurantCalculator; +import christmas.view.inputview.InputValueType; +import christmas.view.inputview.InputView; +import christmas.view.outputview.OutputView; + +public class WootecoRestaurantController { + private final RestaurantCalculator restaurantCalculator; + private final EventPlanerController eventPlanerController; + + public WootecoRestaurantController(RestaurantCalculator restaurantCalculator, + EventPlanerController eventPlanerController) { + this.restaurantCalculator = restaurantCalculator; + this.eventPlanerController = eventPlanerController; + } + + public void takeReservation() { + VisitDate visitDate = getVisitDate(); + Orders orders = getOrders(); + int orderTotalAmount = getOrderTotalAmount(orders); + + showEventPreviewMessage(visitDate); + showOrderDetails(orders, orderTotalAmount); + executeEvent(visitDate, orders, orderTotalAmount); + } + + private VisitDate getVisitDate() { + OutputView.printHelloMessage(); + VisitDate visitDate = inputVisitDate(); + return visitDate; + } + + private Orders getOrders() { + OutputView.printMenu(); + Orders orders = inputOrders(); + return orders; + } + + private int getOrderTotalAmount(Orders orders) { + return restaurantCalculator.getOrderTotalAmount(orders); + } + + private static void showEventPreviewMessage(VisitDate visitDate) { + OutputView.printEventPreviewMessage(visitDate); + } + + private static void showOrderDetails(Orders orders, int orderTotalAmount) { + OutputView.printOrder(orders, orderTotalAmount); + } + + private void executeEvent(VisitDate visitDate, Orders orders, int orderTotalAmount) { + if (canApplyEvent(orderTotalAmount)) { + eventPlanerController.executeEventPlaner(visitDate, orders, orderTotalAmount); + } + } + + private boolean canApplyEvent(int orderTotalAmount) { + if (isOrderTotalAmountValidForEvent(orderTotalAmount)) { + return true; + } + + eventPlanerController.notApplyEvent(orderTotalAmount); + return false; + } + + private static boolean isOrderTotalAmountValidForEvent(int orderTotalAmount) { + return orderTotalAmount >= EVENT_MIN_PAY_AMOUNT.getValue(); + } + + private Orders inputOrders() { + return (Orders) InputView.inputValue(InputValueType.ORDERS); + } + + private VisitDate inputVisitDate() { + return (VisitDate) InputView.inputValue(InputValueType.VISIT_DATE); + } +}
Java
๋งˆ์ฐฌ๊ฐ€์ง€์˜ ์ด์œ ๋กœ, view์—์„œ๋Š” ๋„๋ฉ”์ธ ๋ชจ๋ธ ์ž์ฒด๊ฐ€ ์•„๋‹Œ ๋„๋ฉ”์ธ ๋ชจ๋ธ์˜ ๋ฐ์ดํ„ฐ๋งŒ ์ „๋‹ฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,82 @@ +package christmas.controller; + +import static christmas.domain.event.EventConstants.*; + +import christmas.domain.restaurant.Orders; +import christmas.domain.restaurant.VisitDate; +import christmas.service.RestaurantCalculator; +import christmas.view.inputview.InputValueType; +import christmas.view.inputview.InputView; +import christmas.view.outputview.OutputView; + +public class WootecoRestaurantController { + private final RestaurantCalculator restaurantCalculator; + private final EventPlanerController eventPlanerController; + + public WootecoRestaurantController(RestaurantCalculator restaurantCalculator, + EventPlanerController eventPlanerController) { + this.restaurantCalculator = restaurantCalculator; + this.eventPlanerController = eventPlanerController; + } + + public void takeReservation() { + VisitDate visitDate = getVisitDate(); + Orders orders = getOrders(); + int orderTotalAmount = getOrderTotalAmount(orders); + + showEventPreviewMessage(visitDate); + showOrderDetails(orders, orderTotalAmount); + executeEvent(visitDate, orders, orderTotalAmount); + } + + private VisitDate getVisitDate() { + OutputView.printHelloMessage(); + VisitDate visitDate = inputVisitDate(); + return visitDate; + } + + private Orders getOrders() { + OutputView.printMenu(); + Orders orders = inputOrders(); + return orders; + } + + private int getOrderTotalAmount(Orders orders) { + return restaurantCalculator.getOrderTotalAmount(orders); + } + + private static void showEventPreviewMessage(VisitDate visitDate) { + OutputView.printEventPreviewMessage(visitDate); + } + + private static void showOrderDetails(Orders orders, int orderTotalAmount) { + OutputView.printOrder(orders, orderTotalAmount); + } + + private void executeEvent(VisitDate visitDate, Orders orders, int orderTotalAmount) { + if (canApplyEvent(orderTotalAmount)) { + eventPlanerController.executeEventPlaner(visitDate, orders, orderTotalAmount); + } + } + + private boolean canApplyEvent(int orderTotalAmount) { + if (isOrderTotalAmountValidForEvent(orderTotalAmount)) { + return true; + } + + eventPlanerController.notApplyEvent(orderTotalAmount); + return false; + } + + private static boolean isOrderTotalAmountValidForEvent(int orderTotalAmount) { + return orderTotalAmount >= EVENT_MIN_PAY_AMOUNT.getValue(); + } + + private Orders inputOrders() { + return (Orders) InputView.inputValue(InputValueType.ORDERS); + } + + private VisitDate inputVisitDate() { + return (VisitDate) InputView.inputValue(InputValueType.VISIT_DATE); + } +}
Java
์ด ๋ถ€๋ถ„์€ ๊ตฌ์กฐ ๊ฐœ์„ ์ด ํ•„์š”ํ•˜๊ฒ ๋„ค์š”. ๋ง์”€ํ•ด์ฃผ์‹ ๋Œ€๋กœ ์ปจํŠธ๋กค๋Ÿฌ ๋‚ด๋ถ€์— ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๋‘˜ ํ•„์š”๋Š” ์—†์—ˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. EventPlanerController๋Š” Service์— ๋‘๋Š” ๊ฒŒ ๋งž์•˜๊ฒ ๋„ค์š”. ๋•๋ถ„์— ์–ด๋ ดํ’‹ํ•˜๊ฒŒ ์•Œ์•˜๋˜ ์„œ๋น„์Šค์™€ ์ปจํŠธ๋กค๋Ÿฌ์˜ ์—ญํ• ์— ๋Œ€ํ•ด ๋‹ค์‹œ ํ•œ ๋ฒˆ ์ƒ๊ฐํ•ด๋ณผ ์ˆ˜ ์žˆ๋Š” ๊ธฐํšŒ๊ฐ€ ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,82 @@ +package christmas.controller; + +import static christmas.domain.event.EventConstants.*; + +import christmas.domain.restaurant.Orders; +import christmas.domain.restaurant.VisitDate; +import christmas.service.RestaurantCalculator; +import christmas.view.inputview.InputValueType; +import christmas.view.inputview.InputView; +import christmas.view.outputview.OutputView; + +public class WootecoRestaurantController { + private final RestaurantCalculator restaurantCalculator; + private final EventPlanerController eventPlanerController; + + public WootecoRestaurantController(RestaurantCalculator restaurantCalculator, + EventPlanerController eventPlanerController) { + this.restaurantCalculator = restaurantCalculator; + this.eventPlanerController = eventPlanerController; + } + + public void takeReservation() { + VisitDate visitDate = getVisitDate(); + Orders orders = getOrders(); + int orderTotalAmount = getOrderTotalAmount(orders); + + showEventPreviewMessage(visitDate); + showOrderDetails(orders, orderTotalAmount); + executeEvent(visitDate, orders, orderTotalAmount); + } + + private VisitDate getVisitDate() { + OutputView.printHelloMessage(); + VisitDate visitDate = inputVisitDate(); + return visitDate; + } + + private Orders getOrders() { + OutputView.printMenu(); + Orders orders = inputOrders(); + return orders; + } + + private int getOrderTotalAmount(Orders orders) { + return restaurantCalculator.getOrderTotalAmount(orders); + } + + private static void showEventPreviewMessage(VisitDate visitDate) { + OutputView.printEventPreviewMessage(visitDate); + } + + private static void showOrderDetails(Orders orders, int orderTotalAmount) { + OutputView.printOrder(orders, orderTotalAmount); + } + + private void executeEvent(VisitDate visitDate, Orders orders, int orderTotalAmount) { + if (canApplyEvent(orderTotalAmount)) { + eventPlanerController.executeEventPlaner(visitDate, orders, orderTotalAmount); + } + } + + private boolean canApplyEvent(int orderTotalAmount) { + if (isOrderTotalAmountValidForEvent(orderTotalAmount)) { + return true; + } + + eventPlanerController.notApplyEvent(orderTotalAmount); + return false; + } + + private static boolean isOrderTotalAmountValidForEvent(int orderTotalAmount) { + return orderTotalAmount >= EVENT_MIN_PAY_AMOUNT.getValue(); + } + + private Orders inputOrders() { + return (Orders) InputView.inputValue(InputValueType.ORDERS); + } + + private VisitDate inputVisitDate() { + return (VisitDate) InputView.inputValue(InputValueType.VISIT_DATE); + } +}
Java
์ œ๊ฐ€ ํ•ด๋‹น ๋ถ€๋ถ„์˜ ๊ธฐ๋Šฅ ๊ตฌํ˜„์„ ๊นŒ๋จน๊ณ ์žˆ๋‹ค๊ฐ€ ๋งˆ์ง€๋ง‰์— ํ•˜๊ฒŒ ๋˜์—ˆ๋Š”๋ฐ, ์ด๋Ÿฌํ•œ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋„ค์š”. ๊ธฐ๋ณธ MVC ํŒจํ„ด์˜ ์ปจํŠธ๋กค๋Ÿฌ ์—ญํ• ์„ ์ƒ๊ฐํ•ด๋ณด๋ฉด ์ด๋ฒคํŠธ ๋„๋ฉ”์ธ์ด๋‚˜ ์„œ๋น„์Šค์—์„œ ํ•ด๋‹น ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -8,71 +8,72 @@ import bridge.view.OutputView; public class BridgeGameController { - private final OutputView outputView = new OutputView(); - private final InputView inputView = new InputView(); + private final OutputView outputView; + private final InputView inputView; private BridgeGame bridgeGame; - private boolean isGameEndStatus = false; - private boolean isGameRunning = false; + + public BridgeGameController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } public void play() { outputView.initGame(); Bridge bridge = initBridge(); bridgeGame = new BridgeGame(bridge); - while (!isGameRunning) { + while (bridgeGame.isRunning()) { playOneRound(bridge); } - outputView.printResult(isGameEndStatus, bridgeGame.getTryCount()); + outputView.printResult(bridgeGame.isGameSuccess(), bridgeGame.getTryCount()); + } + + + private void playOneRound(Bridge bridge) { + checkMove(bridge); + bridgeGame.isGameEnd(); + if (bridgeGame.isGameSuccess()) { + return; + } + playOneRound(bridge); + } + + + private void checkMove(Bridge bridge) { + inputMoving(); + outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); + if (!bridgeGame.isRunning()) { + retry(); + } } private Bridge initBridge() { try { int bridgeSize = inputView.readBridgeSize(); - return new Bridge(new BridgeMaker(new BridgeRandomNumberGenerator()).makeBridge(bridgeSize)); + BridgeMaker bridgeMaker = new BridgeMaker(new BridgeRandomNumberGenerator()); + return new Bridge(bridgeMaker.makeBridge(bridgeSize)); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); return initBridge(); } } - private boolean inputMoving() { + private void inputMoving() { try { String moveCommand = inputView.readMoving(); - return bridgeGame.move(moveCommand); + bridgeGame.move(moveCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return inputMoving(); - } - } - - private void playOneRound(Bridge bridge) { - checkMove(bridge); - isGameEndStatus = bridgeGame.isGameEnd(); - if (isGameEndStatus) { - return; - } - playOneRound(bridge); - } - - private void checkMove(Bridge bridge) { - boolean isMove = inputMoving(); - outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); - if (!isMove) { - if (!retry()) { - isGameEndStatus = false; - isGameRunning = false; - return; - } + inputMoving(); } - isGameRunning = true; } - private boolean retry() { + private void retry() { try { String gameCommand = inputView.readGameCommand(); - return bridgeGame.retry(gameCommand); + bridgeGame.retry(gameCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return retry(); + retry(); } }
Java
๋ฉ”์„œ๋“œ์˜ ์—ญํ• ์ด ์กฐ๊ธˆ ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์›€์ง์ž„ ์ž…๋ ฅ์„ ๋ฐ›๋Š” ๋ฉ”์„œ๋“œ์—์„œ `bridgeGame.move()` ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ฒƒ์€ ์กฐ๊ธˆ ์–ด์ƒ‰ํ•ฉ๋‹ˆ๋‹ค!
@@ -8,71 +8,72 @@ import bridge.view.OutputView; public class BridgeGameController { - private final OutputView outputView = new OutputView(); - private final InputView inputView = new InputView(); + private final OutputView outputView; + private final InputView inputView; private BridgeGame bridgeGame; - private boolean isGameEndStatus = false; - private boolean isGameRunning = false; + + public BridgeGameController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } public void play() { outputView.initGame(); Bridge bridge = initBridge(); bridgeGame = new BridgeGame(bridge); - while (!isGameRunning) { + while (bridgeGame.isRunning()) { playOneRound(bridge); } - outputView.printResult(isGameEndStatus, bridgeGame.getTryCount()); + outputView.printResult(bridgeGame.isGameSuccess(), bridgeGame.getTryCount()); + } + + + private void playOneRound(Bridge bridge) { + checkMove(bridge); + bridgeGame.isGameEnd(); + if (bridgeGame.isGameSuccess()) { + return; + } + playOneRound(bridge); + } + + + private void checkMove(Bridge bridge) { + inputMoving(); + outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); + if (!bridgeGame.isRunning()) { + retry(); + } } private Bridge initBridge() { try { int bridgeSize = inputView.readBridgeSize(); - return new Bridge(new BridgeMaker(new BridgeRandomNumberGenerator()).makeBridge(bridgeSize)); + BridgeMaker bridgeMaker = new BridgeMaker(new BridgeRandomNumberGenerator()); + return new Bridge(bridgeMaker.makeBridge(bridgeSize)); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); return initBridge(); } } - private boolean inputMoving() { + private void inputMoving() { try { String moveCommand = inputView.readMoving(); - return bridgeGame.move(moveCommand); + bridgeGame.move(moveCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return inputMoving(); - } - } - - private void playOneRound(Bridge bridge) { - checkMove(bridge); - isGameEndStatus = bridgeGame.isGameEnd(); - if (isGameEndStatus) { - return; - } - playOneRound(bridge); - } - - private void checkMove(Bridge bridge) { - boolean isMove = inputMoving(); - outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); - if (!isMove) { - if (!retry()) { - isGameEndStatus = false; - isGameRunning = false; - return; - } + inputMoving(); } - isGameRunning = true; } - private boolean retry() { + private void retry() { try { String gameCommand = inputView.readGameCommand(); - return bridgeGame.retry(gameCommand); + bridgeGame.retry(gameCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return retry(); + retry(); } }
Java
๊ฐœ์ธ์ ์œผ๋กœ ์ด ๋ถ€๋ถ„์˜ ํ๋ฆ„ ์ฒ˜๋ฆฌ๊ฐ€ ์กฐ๊ธˆ ์•„์‰ฝ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ์šฐ์„  ์•„๋ž˜์˜ `inputMoving()` ๋ฉ”์„œ๋“œ์˜ ์—ญํ• ์ด ์กฐ๊ธˆ ๋งŽ๊ณ  , `playOneRount()`๋ฅผ ๋ฐ˜๋ณตํ•˜๋Š” ๋กœ์ง๋„ while ๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด ์ข€ ๋” ์ง๊ด€์ ์œผ๋กœ ๋ณด์ด์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค! ํ•œ๋ฒˆ์ฏค ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -8,71 +8,72 @@ import bridge.view.OutputView; public class BridgeGameController { - private final OutputView outputView = new OutputView(); - private final InputView inputView = new InputView(); + private final OutputView outputView; + private final InputView inputView; private BridgeGame bridgeGame; - private boolean isGameEndStatus = false; - private boolean isGameRunning = false; + + public BridgeGameController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } public void play() { outputView.initGame(); Bridge bridge = initBridge(); bridgeGame = new BridgeGame(bridge); - while (!isGameRunning) { + while (bridgeGame.isRunning()) { playOneRound(bridge); } - outputView.printResult(isGameEndStatus, bridgeGame.getTryCount()); + outputView.printResult(bridgeGame.isGameSuccess(), bridgeGame.getTryCount()); + } + + + private void playOneRound(Bridge bridge) { + checkMove(bridge); + bridgeGame.isGameEnd(); + if (bridgeGame.isGameSuccess()) { + return; + } + playOneRound(bridge); + } + + + private void checkMove(Bridge bridge) { + inputMoving(); + outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); + if (!bridgeGame.isRunning()) { + retry(); + } } private Bridge initBridge() { try { int bridgeSize = inputView.readBridgeSize(); - return new Bridge(new BridgeMaker(new BridgeRandomNumberGenerator()).makeBridge(bridgeSize)); + BridgeMaker bridgeMaker = new BridgeMaker(new BridgeRandomNumberGenerator()); + return new Bridge(bridgeMaker.makeBridge(bridgeSize)); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); return initBridge(); } } - private boolean inputMoving() { + private void inputMoving() { try { String moveCommand = inputView.readMoving(); - return bridgeGame.move(moveCommand); + bridgeGame.move(moveCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return inputMoving(); - } - } - - private void playOneRound(Bridge bridge) { - checkMove(bridge); - isGameEndStatus = bridgeGame.isGameEnd(); - if (isGameEndStatus) { - return; - } - playOneRound(bridge); - } - - private void checkMove(Bridge bridge) { - boolean isMove = inputMoving(); - outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); - if (!isMove) { - if (!retry()) { - isGameEndStatus = false; - isGameRunning = false; - return; - } + inputMoving(); } - isGameRunning = true; } - private boolean retry() { + private void retry() { try { String gameCommand = inputView.readGameCommand(); - return bridgeGame.retry(gameCommand); + bridgeGame.retry(gameCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return retry(); + retry(); } }
Java
> ๊ฐœ์ธ์ ์œผ๋กœ ์ด ๋ถ€๋ถ„์˜ ํ๋ฆ„ ์ฒ˜๋ฆฌ๊ฐ€ ์กฐ๊ธˆ ์•„์‰ฝ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ์šฐ์„  ์•„๋ž˜์˜ `inputMoving()` ๋ฉ”์„œ๋“œ์˜ ์—ญํ• ์ด ์กฐ๊ธˆ ๋งŽ๊ณ  , `playOneRount()`๋ฅผ ๋ฐ˜๋ณตํ•˜๋Š” ๋กœ์ง๋„ while ๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด ์ข€ ๋” ์ง๊ด€์ ์œผ๋กœ ๋ณด์ด์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค! ํ•œ๋ฒˆ์ฏค ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ๊ธฐ์กด์— ์žฌ๊ท€๋กœ ๊ตฌ์„ฑํ–ˆ๋˜ ์ฝ”๋“œ๋ฅผ while๋กœ ๋ฐ”๊ฟ€ ์ƒ๊ฐ์„ ๋ชปํ–ˆ๋„ค์š”.. ๊ตณ์ด ์กฐ๊ฑด๊ฑธ์–ด์„œ ์žฌ๊ท€๋ฅผ ํ•˜๊ธฐ๋ณด๋‹ค ์˜๊ฒฌ์ฃผ์‹  while์„ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ํ™•์‹คํžˆ ๋” ์ข‹์•„๋ณด์ด๊ธด ํ•ฉ๋‹ˆ๋‹ค ! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -8,71 +8,72 @@ import bridge.view.OutputView; public class BridgeGameController { - private final OutputView outputView = new OutputView(); - private final InputView inputView = new InputView(); + private final OutputView outputView; + private final InputView inputView; private BridgeGame bridgeGame; - private boolean isGameEndStatus = false; - private boolean isGameRunning = false; + + public BridgeGameController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } public void play() { outputView.initGame(); Bridge bridge = initBridge(); bridgeGame = new BridgeGame(bridge); - while (!isGameRunning) { + while (bridgeGame.isRunning()) { playOneRound(bridge); } - outputView.printResult(isGameEndStatus, bridgeGame.getTryCount()); + outputView.printResult(bridgeGame.isGameSuccess(), bridgeGame.getTryCount()); + } + + + private void playOneRound(Bridge bridge) { + checkMove(bridge); + bridgeGame.isGameEnd(); + if (bridgeGame.isGameSuccess()) { + return; + } + playOneRound(bridge); + } + + + private void checkMove(Bridge bridge) { + inputMoving(); + outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); + if (!bridgeGame.isRunning()) { + retry(); + } } private Bridge initBridge() { try { int bridgeSize = inputView.readBridgeSize(); - return new Bridge(new BridgeMaker(new BridgeRandomNumberGenerator()).makeBridge(bridgeSize)); + BridgeMaker bridgeMaker = new BridgeMaker(new BridgeRandomNumberGenerator()); + return new Bridge(bridgeMaker.makeBridge(bridgeSize)); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); return initBridge(); } } - private boolean inputMoving() { + private void inputMoving() { try { String moveCommand = inputView.readMoving(); - return bridgeGame.move(moveCommand); + bridgeGame.move(moveCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return inputMoving(); - } - } - - private void playOneRound(Bridge bridge) { - checkMove(bridge); - isGameEndStatus = bridgeGame.isGameEnd(); - if (isGameEndStatus) { - return; - } - playOneRound(bridge); - } - - private void checkMove(Bridge bridge) { - boolean isMove = inputMoving(); - outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); - if (!isMove) { - if (!retry()) { - isGameEndStatus = false; - isGameRunning = false; - return; - } + inputMoving(); } - isGameRunning = true; } - private boolean retry() { + private void retry() { try { String gameCommand = inputView.readGameCommand(); - return bridgeGame.retry(gameCommand); + bridgeGame.retry(gameCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return retry(); + retry(); } }
Java
> ๋ฉ”์„œ๋“œ์˜ ์—ญํ• ์ด ์กฐ๊ธˆ ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์›€์ง์ž„ ์ž…๋ ฅ์„ ๋ฐ›๋Š” ๋ฉ”์„œ๋“œ์—์„œ `bridgeGame.move()` ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ฒƒ์€ ์กฐ๊ธˆ ์–ด์ƒ‰ํ•ฉ๋‹ˆ๋‹ค! ์Œ.. ๊ทธ๋Ÿด๊นŒ์š” ? ๋ฉ”์„œ๋“œ ๋ช…์ด ์–ด์ƒ‰ํ•œ๊ฑธ๊นŒ์š” ๋ฉ”์„œ๋“œ ์—ญํ• ์ด ๋ฌธ์ œ์ผ๊นŒ์š” ? ์ €๋Š” ์ปจํŠธ๋กค๋Ÿฌ๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ '์ž…๋ ฅ์„ ํ†ตํ•ด์„œ ์‹คํ–‰ํ•œ๋‹ค' ๊ฐ€ ํ•˜๋‚˜์˜ ์—ญํ• ์„ ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๊ทธ๊ฒŒ ์•„๋‹ˆ์—ˆ์„๊นŒ์š”.. ์ •๋ง ์–ด๋ ต๊ธดํ•˜๋„ค์š”
@@ -8,71 +8,72 @@ import bridge.view.OutputView; public class BridgeGameController { - private final OutputView outputView = new OutputView(); - private final InputView inputView = new InputView(); + private final OutputView outputView; + private final InputView inputView; private BridgeGame bridgeGame; - private boolean isGameEndStatus = false; - private boolean isGameRunning = false; + + public BridgeGameController(OutputView outputView, InputView inputView) { + this.outputView = outputView; + this.inputView = inputView; + } public void play() { outputView.initGame(); Bridge bridge = initBridge(); bridgeGame = new BridgeGame(bridge); - while (!isGameRunning) { + while (bridgeGame.isRunning()) { playOneRound(bridge); } - outputView.printResult(isGameEndStatus, bridgeGame.getTryCount()); + outputView.printResult(bridgeGame.isGameSuccess(), bridgeGame.getTryCount()); + } + + + private void playOneRound(Bridge bridge) { + checkMove(bridge); + bridgeGame.isGameEnd(); + if (bridgeGame.isGameSuccess()) { + return; + } + playOneRound(bridge); + } + + + private void checkMove(Bridge bridge) { + inputMoving(); + outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); + if (!bridgeGame.isRunning()) { + retry(); + } } private Bridge initBridge() { try { int bridgeSize = inputView.readBridgeSize(); - return new Bridge(new BridgeMaker(new BridgeRandomNumberGenerator()).makeBridge(bridgeSize)); + BridgeMaker bridgeMaker = new BridgeMaker(new BridgeRandomNumberGenerator()); + return new Bridge(bridgeMaker.makeBridge(bridgeSize)); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); return initBridge(); } } - private boolean inputMoving() { + private void inputMoving() { try { String moveCommand = inputView.readMoving(); - return bridgeGame.move(moveCommand); + bridgeGame.move(moveCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return inputMoving(); - } - } - - private void playOneRound(Bridge bridge) { - checkMove(bridge); - isGameEndStatus = bridgeGame.isGameEnd(); - if (isGameEndStatus) { - return; - } - playOneRound(bridge); - } - - private void checkMove(Bridge bridge) { - boolean isMove = inputMoving(); - outputView.printMap(bridgeGame.getUserBridge().getUserBridge(), bridge.getBridge()); - if (!isMove) { - if (!retry()) { - isGameEndStatus = false; - isGameRunning = false; - return; - } + inputMoving(); } - isGameRunning = true; } - private boolean retry() { + private void retry() { try { String gameCommand = inputView.readGameCommand(); - return bridgeGame.retry(gameCommand); + bridgeGame.retry(gameCommand); } catch (IllegalArgumentException e) { outputView.printErrorMessage(e.getMessage()); - return retry(); + retry(); } }
Java
๊ทธ๋ ‡๊ฒŒ ํ•˜๋‚˜๋กœ ๋ณผ ์ˆ˜๋„ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ๋‹ค๋งŒ ์ œ๊ฐ€ ์ƒ๊ฐํ–ˆ์„ ๋•Œ๋Š” ์ž…๋ ฅ ๋ฐ›๊ธฐ -> ์›€์ง์ธ๋‹ค ๊นŒ์ง€๊ฐ€ ํ•˜๋‚˜์˜ round ๋กœ ๋ฌถ์ด๊ณ , isSuccess(๋์— ๋„๋‹ฌํ•จ) ๋‚˜ ๋–จ์–ด์ง ์ƒํƒœ๊ฐ€ ๋˜์—ˆ์„ ๋•Œ ๋‹ค์‹œ ํ๋ฆ„์„ ์ œ์–ดํ•˜๋Š” ๋กœ์ง์ด ํ•˜๋‚˜์˜ ๋” ํฐ ๋ฉ”์„œ๋“œ๋กœ round๋ฅผ ๋ฐ˜๋ณต์‹œํ‚ค๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค! ์ •๋‹ต์€ ์—†์œผ๋‹ˆ ํ•œ๋ฒˆ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๊ณ  ๋” ์ ์ ˆํ•˜๋‹ค๊ณ  ๋А๋ผ๋Š” ๊ตฌ์กฐ๋ฅผ ์žก์•„๊ฐ€๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,47 @@ +package bridge.view; + +import java.util.List; +import java.util.StringJoiner; + +public class StringUtil { + + public static String createBridge(List<String> userBridge, List<String> gameBridge) { + StringJoiner bridge = new StringJoiner("\n"); + + StringJoiner upBridge = new StringJoiner(" | "); + StringJoiner downBridge = new StringJoiner(" | "); + + for (int i = 0; i < userBridge.size(); i++) { + addBridgeSegment(userBridge.get(i), gameBridge.get(i), upBridge, downBridge); + } + return bridge.add(String.format("[ %s ]", upBridge)).add(String.format("[ %s ]", downBridge)).toString(); + } + + private static void addBridgeSegment(String userSegment, String gameSegment, StringJoiner upBridge, StringJoiner downBridge) { + if (userSegment.equals(gameSegment)) { + addMatchingSegment(userSegment, upBridge, downBridge); + } else { + addNonMatchingSegment(userSegment, upBridge, downBridge); + } + } + + private static void addMatchingSegment(String segment, StringJoiner upBridge, StringJoiner downBridge) { + if (segment.equals("U")) { + upBridge.add("O"); + downBridge.add(" "); + } else if (segment.equals("D")) { + upBridge.add(" "); + downBridge.add("O"); + } + } + + private static void addNonMatchingSegment(String segment, StringJoiner upBridge, StringJoiner downBridge) { + if (segment.equals("U")) { + upBridge.add("X"); + downBridge.add(" "); + } else if (segment.equals("D")) { + upBridge.add(" "); + downBridge.add("X"); + } + } +}
Java
๋ฌธ์ž์—ด๋“ค์„ StringUtil ์„ ๊ตฌํ˜„ํ•ด์„œ OutputView์˜ ์ฑ…์ž„์„ ๋œ์–ด์ค€ ๊ฑด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ๋‹ค๋งŒ ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋‹ค์†Œ ๋งŽ๊ณ , ๋ชจ๋“  ๊ฒฐ๊ณผ์— ๋Œ€ํ•œ ๊ฒฐ๊ณผ ๋น„๊ต๋ฅผ StringUtil์—์„œ ๋‹ค ํ•˜๊ณ  ์žˆ๋Š” ๋ถ€๋ถ„์€ ์กฐ๊ธˆ ์•„์‰ฌ์šด ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ์„œ๋น„์Šค ๊ณ„์ธต์—์„œ ์–ด๋А์ •๋„ ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ€๊ณตํ•ด์„œ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋„๋ก ๊ตฌํ˜„ํ•˜๋ฉด ์–ด๋–จ๊นŒ ์‹ถ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,47 @@ +package bridge.view; + +import java.util.List; +import java.util.StringJoiner; + +public class StringUtil { + + public static String createBridge(List<String> userBridge, List<String> gameBridge) { + StringJoiner bridge = new StringJoiner("\n"); + + StringJoiner upBridge = new StringJoiner(" | "); + StringJoiner downBridge = new StringJoiner(" | "); + + for (int i = 0; i < userBridge.size(); i++) { + addBridgeSegment(userBridge.get(i), gameBridge.get(i), upBridge, downBridge); + } + return bridge.add(String.format("[ %s ]", upBridge)).add(String.format("[ %s ]", downBridge)).toString(); + } + + private static void addBridgeSegment(String userSegment, String gameSegment, StringJoiner upBridge, StringJoiner downBridge) { + if (userSegment.equals(gameSegment)) { + addMatchingSegment(userSegment, upBridge, downBridge); + } else { + addNonMatchingSegment(userSegment, upBridge, downBridge); + } + } + + private static void addMatchingSegment(String segment, StringJoiner upBridge, StringJoiner downBridge) { + if (segment.equals("U")) { + upBridge.add("O"); + downBridge.add(" "); + } else if (segment.equals("D")) { + upBridge.add(" "); + downBridge.add("O"); + } + } + + private static void addNonMatchingSegment(String segment, StringJoiner upBridge, StringJoiner downBridge) { + if (segment.equals("U")) { + upBridge.add("X"); + downBridge.add(" "); + } else if (segment.equals("D")) { + upBridge.add(" "); + downBridge.add("X"); + } + } +}
Java
๋งž๋Š”๋ง์ธ๊ฑฐ๊ฐ™์Šต๋‹ˆ๋‹ค.. ์ธ์ž๊ฐ€ 4๊ฐœ๋‚˜ ๋˜๋‹ค๋ณด๋‹ˆ ์ •๋ง ๋ง˜์— ์•ˆ๋“œ๋Š” ๋ฉ”์„œ๋“œ์˜€๋Š”๋ฐ์š” ์—ฌ๊ธธ ๋ฆฌํŒฉํ† ๋ง ํ•˜๋ ค๊ณ ํ•˜๋‹ˆ map์„ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ํ•ด์•ผํ–ˆ๋Š”๋ฐ ๊ณ„์† ๋ฆฌํŒฉํ† ๋ง ๋„์ „ํ•ด๋ดค๋Š”๋ฐ ๊ธฐ์กด ๊ตฌ์กฐ๋ฅผ ๊นจ๊ณ  ๋งŒ๋“ค์–ด์•ผ๋˜๋Š” ๋ถ€๋ถ„์ด ์กด์žฌํ•ด์„œ ๊ธฐ์กด๊ตฌ์กฐ ์œ ์ง€ํ•˜๊ณ  ๊ฐ€๋А๋ผ ์•„์‰ฌ์šด ๋ถ€๋ถ„์ด ๋‚˜์˜จ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹คใ…œใ…œ
@@ -0,0 +1,74 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.message.ErrorMessage; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class ChristmasPromotionController { + private EventCalendar eventCalendar; + private VisitDate visitDate; + private Menu menu; + private Event event; + private StarDate starDate; + + public void run() { + eventCalendarSetting(2023, 12); + starDateSetting(); + visitDate(); + menuSetting(); + eventSetting(); + result(); + } + + private void eventCalendarSetting(int year, int month) { + this.eventCalendar = new EventCalendar(year, month); + } + + private void starDateSetting() { + this.starDate = new StarDate(eventCalendar); + } + + private void visitDate() { + OutputView.printStart(); + while (true) { + try { + this.visitDate = VisitDate.of(InputView.readDate(), this.eventCalendar); + return; + } catch (IllegalArgumentException e) { + OutputView.printErrorMessage(ErrorMessage.INVALID_DATE.getFormattedMessage()); + System.out.println(e.getMessage()); + System.out.println(); + } + } + } + + private void menuSetting() { + while (true) { + try { + this.menu = new Menu(InputView.readMenu()); + return; + } catch (IllegalArgumentException e) { + OutputView.printErrorMessage(ErrorMessage.INVALID_ORDER.getFormattedMessage()); + System.out.println(e.getMessage()); + OutputView.printAllMenu(e.getMessage()); + System.out.println(); + } + } + } + + private void eventSetting() { + this.event = new Event(); + this.event.eventSetting(visitDate, eventCalendar, starDate, menu); + } + + private void result() { + OutputView.printSelectMenu(menu); + OutputView.printBeforeDiscountMenuTotalPrice(menu); + OutputView.printGift(event); + OutputView.printBenefitHistory(event); + OutputView.printBenefitsAllAmount(event); + OutputView.printAfterDiscount(menu, event); + OutputView.printBadge(event, eventCalendar); + } +}
Java
`InputView` ์—์„œ `CommonValidator` ๋ฅผ ํ†ตํ•ด์„œ ๊ฒ€์ฆ์„ ํ•˜๋Š”๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด `InputValidator` ์—์„œ ์ถ”๊ฐ€์ ์ธ ๊ฒ€์ฆ๋„ ํ•จ๊ป˜ ์ง„ํ–‰ํ•ด์„œ ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ์‹์œผ๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? ์ €๋Š” ์ž…๋ ฅ์„ ๋‹ด๋‹นํ•˜๋Š” ํด๋ž˜์Šค์—์„œ ์ž…๋ ฅ์„ ๋ฐ›๊ณ  ๊ฒ€์ฆ ํด๋ž˜์Šค๋ฅผ ํ†ตํ•ด ๊ฒ€์ฆํ›„ ์˜ˆ์™ธ๊นŒ์ง€ ๋˜์ง€๋„๋ก ๊ตฌํ˜„ํ–ˆ๋”๋‹ˆ ๊น”๋”ํ•˜๊ฒŒ ๊ตฌํ˜„ํ–ˆ๋˜๊ฑฐ ๊ฐ™์•„์„œ ์—ฌ์ญค๋ด…๋‹ˆ๋‹ค!