code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -1,7 +1,16 @@ package store; +import store.controller.Screen; +import store.view.InputView; +import store.view.OutputView; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + try { + Screen screen = new Screen(new InputView(), new OutputView()); + screen.run(); + } catch (IllegalArgumentException e) { + System.out.println("[ERROR] " + e.getMessage()); + } } }
Java
์—๋Ÿฌ ๋ฉ”์„ธ์ง€๋ฅผ ๋„์šฐ๊ณ  ํ•ด๋‹น ์œ„์น˜์—์„œ ๋‹ค์‹œ ์‹œ์ž‘์„ ํ•ด์•ผํ•˜๋Š”๋ฐ ๊ทธ ๋ถ€๋ถ„์ด ๋น ์ง„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ ์—๋Ÿฌ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ถ€๋ถ„๋„ ๊ฒฐ๊ตญ view์—์„œ ํ•ด์ค˜์•ผํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,16 @@ +package store.constant; + +public enum MembershipDiscount { + MAX_DISCOUNT(8000), + DISCOUNT_RATE(0.3); + + private final double value; + + MembershipDiscount(double value) { + this.value = value; + } + + public double getValue() { + return value; + } +}
Java
8000๋„ double์„ ์ด์šฉํ•˜๊ธฐ์—๋Š” ๋ณ„๋กœ ์ข‹์ง€์•Š์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•„๋“œ์— ์ €์žฅํ•˜๊ฑฐ๋‚˜ ์ผ๋ฐ˜ ํด๋ž˜์Šค์˜ ํ•„๋“œ๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,22 @@ +package store.constant; + +public enum StockState { + NO_STOCK("0", "์žฌ๊ณ  ์—†์Œ"), + HAVE_STOCK("1", ""); + + private final String message; + private final String stockState; + + StockState(String message, String stockState) { + this.message = message; + this.stockState = stockState; + } + + public static String getMatchingState(String findAnswer) { + if (NO_STOCK.message.equals(findAnswer)) { + return NO_STOCK.stockState; + } + findAnswer = String.format("%,d", Integer.parseInt(findAnswer)); + return findAnswer + "๊ฐœ"; + } +}
Java
enum์˜ ์„ฑํ–ฅ๋ณด๋‹ค๋Š” ๊ทธ๋ƒฅ ์žฌ๊ณ  ์ƒํƒœ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋А๋‚Œ์ด ๋“ค์–ด ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์—์„œ ๊ตณ์ด ๋บ„ ํ•„์š”๊ฐ€ ์žˆ๋ƒ๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์š”
@@ -0,0 +1,25 @@ +package store.constant; + +import store.exception.InvalidFormException; + +public enum YesNo { + YES("Y", true), + NO("N", false); + + private final String message; + private final boolean answer; + + YesNo(String message, Boolean answer) { + this.message = message; + this.answer = answer; + } + + public static boolean getMatchingAnswer(String findAnswer) { + for (YesNo yesNo : YesNo.values()) { + if (yesNo.message.equals(findAnswer)) { + return yesNo.answer; + } + } + throw new InvalidFormException(); + } +}
Java
์ด์ฒ˜๋Ÿผ ๋ฉ”์„œ๋“œ ํ•˜๋‚˜๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์„ enum์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
์ปจํŠธ๋กค๋Ÿฌ๋Š” ํด๋ž˜์Šค ์ด๋ฆ„์— ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ ์žˆ์–ด์•ผ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ํ•˜๋‚˜์˜ ๋„๋ฉ”์ธ์— ์„œ๋น„์Šค, ์ปจํŠธ๋กค๋Ÿฌ์™€ ๊ฐ™์€ ๋‹ค์–‘ํ•œ ๊ฒƒ๋“ค์ด ์žˆ์–ด ์ด๋ฆ„์„ ์ง“๊ธฐ์— ๋” ํŽธํ•ด์งˆ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
\n์€ ```System.lineSeparator()```์„ ์‚ฌ์šฉํ•ด์„œ ๋‹ค์–‘ํ•œ os์— ํ˜ธํ™˜์ด ๋˜๋„๋ก ๋งŒ๋“ค ์ˆ˜ ์žˆ์–ด์š”
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
์‚ฌ์šฉ์ž๊ฐ€ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ๊ณณ์— ์ฝ”๋“œ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์˜ค๋ฅ˜๋Š” ์•ˆ๋œจ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
,์™€ \n์€ ์ƒ์ˆ˜ํ™”๋ฅผ ์‹œํ‚ค๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
๋งต์„ ์—”ํŠธ๋ฆฌ๋กœ ์š”์†Œ๋ฅผ ๋ฝ‘์•„์˜ค๊ธฐ๋ณด๋‹ค๋Š” ํ‚ค๋กœ ๋ฝ‘์•„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ๊ฐ€๋…์„ฑ์ด ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
๊ฐœ์ธ์ ์œผ๋กœ forEach๋ฅผ ์‚ฌ์šฉํ• ๋•Œ ๋‚ด๋ถ€ํ•จ์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ ์ค„์ธ ๊ฒฝ์šฐ ๋‚ด๋ถ€ ํ•จ์ˆ˜๋Š” ๋”ฐ๋กœ ๋ฉ”์„œ๋“œ๋กœ ๋ฝ‘์•„๋‚ด๊ฑฐ๋‚˜ for์„ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋” ๋‚˜์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
ํŒŒ์ผ์˜ ์œ„์น˜๊ฐ€ ๋”ฐ๋กœ ์ƒ์ˆ˜๋กœ ์ง€์ •๋˜์–ด์žˆ์œผ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ skip(1)๋„ 1์„ ์ƒ์ˆ˜๋กœ ๋ถ€์—ฌํ•˜๋ฉฐ ์ด๋ฆ„์„ ์˜๋ฏธ์žˆ๊ฒŒ ์ง€์–ด ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์ด ์ฝ์„ ๋•Œ ์˜๋ฏธ๋ฅผ ์ „๋‹ฌํ•˜๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
-1์€ ์—†์–ด๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,159 @@ +package store.controller; + +import store.constant.ProductState; +import store.model.*; +import store.util.Reader; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Screen { + public static final String PRODUCT_FILE_CATEGORY = "name,price,quantity,promotion\n"; + + private final InputView inputView; + private final OutputView outputView; + + + public Screen(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + do { + Store store = bringProducts(); + outputView.printStoreMenu(store); + + Orders orders = askProductAndPrice(store); + checkProducts(orders, store); + + Receipt receipt = store.getReceipt(askGetMembership()); + outputView.printReceipt(orders, store, receipt); + updateStockResult(store); + } while (askAdditionalPurchase()); + } + + public void checkProducts(Orders orders, Store store) { + for (Order order : orders.getOrders()) { + ProductState productState = store.getProductState(order); + if (productState == ProductState.NO_PROMOTION_PERIOD) { + continue; + } + calculateWhenPromotionPeriod(order, store, productState); + } + } + + private void calculateWhenPromotionPeriod(Order order, Store store, ProductState productState) { + if (productState == ProductState.GET_ONE_FREE) { + store.calculateWhenGetOneFreeCase(order, askGetOneFree(order)); + return; + } + if (productState == ProductState.BUY_ORIGINAL_PRICE) { + store.calculateWhenBuyOriginalPrice(order, askBuyOriginalPrice(order, store.countBuyOriginalPrice(order))); + return; + } + if (productState == ProductState.NOTHING_TO_ASK) { + store.calculateWhenNothingToAsk(order); + } + } + + private Orders askProductAndPrice(Store store) { + return Task.repeatUntilValid(() -> { + String input = inputView.getProductAndPrice(); + return makeValidateOrder(input, store); + }); + } + + private boolean askGetOneFree(Order order) { + return Task.repeatUntilValid(() -> inputView.getOneMoreFree(order)); + } + + private boolean askBuyOriginalPrice(Order order, int itemsAtOriginalPriceCount) { + return Task.repeatUntilValid(() -> inputView.getPurchaseOrNot(order.getName(), itemsAtOriginalPriceCount)); + } + + private boolean askGetMembership() { + return Task.repeatUntilValid(inputView::getMembershipDiscountOrNot); + } + + private boolean askAdditionalPurchase() { + return Task.repeatUntilValid(inputView::getAdditionalPurchase); + } + + private Orders makeValidateOrder(String input, Store store) { + String[] inputProducts = input.split(",", -1); + Orders orders = new Orders(); + orders.addProduct(inputProducts, store); + return orders; + } + + private Store bringProducts() { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/products.md").stream().skip(1).toList(); + List<Product> promotionProducts = new ArrayList<>(); + List<Product> normalProducts = new ArrayList<>(); + lines.forEach(line -> updateProducts(line, promotionProducts, normalProducts)); + return makeValidStore(promotionProducts, normalProducts); + } + + private void updateProducts(String line, List<Product> promotionProducts, List<Product> normalProducts) { + Product product = new Product(line); + if (product.isPromotion()) { + promotionProducts.add(product); + return; + } + normalProducts.add(product); + } + + private Store makeValidStore(List<Product> promotionProducts, List<Product> normalProducts) { + Store store = new Store(); + promotionProducts.forEach(promotion -> { + Product normal = getNormalProduct(normalProducts, promotion); + normalProducts.remove(normal); + store.addProduct(promotion.getName(), new Products(List.of(promotion, normal))); + }); + normalProducts.forEach(normal -> + store.addProduct(normal.getName(), new Products(List.of(normal))) + ); + return store; + } + + private void updateStockResult(Store store) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + writer.write(PRODUCT_FILE_CATEGORY); + for (Map.Entry<String, Products> mapElement : store.getStoreProducts().entrySet()) { + writeProducts(writer, mapElement.getValue()); + } + writer.close(); + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private void writeProducts(BufferedWriter writer, Products products) { + try { + for (Product product : products.getProducts()) { + writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity() + "," + product.getPromotion() + "\n"); + } + } catch (IOException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + private Product getNormalProduct(List<Product> normalProducts, Product promotionProduct) { + for (Product normal : normalProducts) { + if (normal.getName().equals(promotionProduct.getName())) { + return normal; + } + } + return new Product( + promotionProduct.getName() + "," + promotionProduct.getPrice() + ",0,null"); + } +} +
Java
```suggestion if (productState != ProductState.NO_PROMOTION_PERIOD) { calculateWhenPromotionPeriod(order, store, productState); } ``` ์œ„์™€ ๊ฐ™์ด ๊ณ ์น˜๋Š” ๊ฒƒ์ด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,7 @@ +package store.exception; + +public class InvalidDuplicateOrder extends IllegalArgumentException { + public InvalidDuplicateOrder() { + super("[ERROR] ์ค‘๋ณต๋˜๋Š” ์ƒํ’ˆ์„ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } +}
Java
[ERROR]์€ ์—๋Ÿฌ์ถœ๋ ฅ ํ˜•์‹์ด๋‹ˆ ์—๋Ÿฌ๋ฅผ ์ถœ๋ ฅํ• ๋•Œ ํ•ฉ์ณ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ ์—๋Ÿฌ ๋ฉ”์„ธ์ง€๋ฅผ ํ•œ๊ณณ์— ๋ชจ์•„๋‘๋Š”๊ฒŒ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. enum์‚ฌ์šฉํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,7 @@ +package store.exception; + +public class InvalidDuplicateOrder extends IllegalArgumentException { + public InvalidDuplicateOrder() { + super("[ERROR] ์ค‘๋ณต๋˜๋Š” ์ƒํ’ˆ์„ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } +}
Java
ํ•˜๋‚˜์˜ ์ปค์Šคํ…€ Exception์„ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ์—ฌ๋Ÿฌ๊ฐ€์ง€๋กœ ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,19 @@ +package store.model; + +public class GiftProduct { + private final String name; + private final int quantity; + + public GiftProduct(Product promotion, int possibleGiftProducts) { + this.name = promotion.getName(); + this.quantity = possibleGiftProducts / promotion.getPromotionCount(); + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } +}
Java
์•ž์—์„œ ์ถ”๊ฐ€์ ์œผ๋กœ ์—ฐ์‚ฐํ•˜๊ณ  ๋‹ค์‹œ ์›๋ž˜๋Œ€๋กœ ๋˜๋Œ๋ฆฌ๋Š” ์—ฐ์‚ฐ์€ ๋น„ํšจ์œจ์ ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค...
@@ -0,0 +1,19 @@ +package store.model; + +public class GiftProduct { + private final String name; + private final int quantity; + + public GiftProduct(Product promotion, int possibleGiftProducts) { + this.name = promotion.getName(); + this.quantity = possibleGiftProducts / promotion.getPromotionCount(); + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } +}
Java
๋งŒ์ผ ์—ฐ์‚ฐ์ด ์™„๋ฃŒ๋œ ์ƒํƒœ๋กœ ์ˆœ์ˆ˜ ๋ฐ์ดํ„ฐ ์ €์žฅ์„ ์œ„ํ•œ ๊ฒƒ์ด๋ผ๋ฉด record๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋‹ˆ ์ด ๋ถ€๋ถ„๋„ ์ฐธ๊ณ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,65 @@ +package store.model; + +import store.util.Parser; + +public class Product { + private final String name; + private final int price; + private int quantity; + private final String promotion; + private final PromotionPolicy promotionPolicy; + + public Product(String line) { + String[] product = line.split(","); + this.name = product[0]; + this.price = Parser.parseToInt(product[1]); + this.quantity = Parser.parseToInt(product[2]); + this.promotion = product[3]; + promotionPolicy = new PromotionPolicy(promotion); + } + + public boolean isPromotionBenefitPossibleLeft(Order order) { + int promotionRemainingCount = getNoPromotionBenefit(order.getQuantity()); + return promotionRemainingCount == getPromotionBuyCount(); + } + + public void reduceStock(int num) { + quantity -= num; + } + + public boolean isPromotion() { + return !promotion.equals("null"); + } + + public boolean isPromotionPeriod() { + return promotionPolicy.isValidPeriod(); + } + + public int getNoPromotionBenefit(int num) { + return num % getPromotionCount(); + } + + public int getPromotionCount() { + return promotionPolicy.getPromotionCount(); + } + + public int getPromotionBuyCount() { + return promotionPolicy.getPromotionBuyCount(); + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getQuantity() { + return quantity; + } + + public String getPromotion() { + return promotion; + } +}
Java
์ €๋„ ์ด๋ ‡๊ฒŒ ๋งŒ๋“œ๋Š” ๊ฒƒ์„ ์ƒ๊ฐํ•ด๋ดค๋Š”๋ฐ ์ด ๋ถ€๋ถ„์ด View์™€ model์˜ ๊ฒฝ๊ณ„์— ์žˆ๋Š” ๋ถ€๋ถ„ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ €๋Š” view์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์ •์ œํ•˜์—ฌ dto๋ฅผ ํ†ตํ•ด ์ „๋‹ฌํ•˜๋Š” ๊ฒƒ๋„ ๋‚˜์˜์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ hayeoungLee๋‹˜์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,65 @@ +package store.model; + +import store.util.Parser; + +public class Product { + private final String name; + private final int price; + private int quantity; + private final String promotion; + private final PromotionPolicy promotionPolicy; + + public Product(String line) { + String[] product = line.split(","); + this.name = product[0]; + this.price = Parser.parseToInt(product[1]); + this.quantity = Parser.parseToInt(product[2]); + this.promotion = product[3]; + promotionPolicy = new PromotionPolicy(promotion); + } + + public boolean isPromotionBenefitPossibleLeft(Order order) { + int promotionRemainingCount = getNoPromotionBenefit(order.getQuantity()); + return promotionRemainingCount == getPromotionBuyCount(); + } + + public void reduceStock(int num) { + quantity -= num; + } + + public boolean isPromotion() { + return !promotion.equals("null"); + } + + public boolean isPromotionPeriod() { + return promotionPolicy.isValidPeriod(); + } + + public int getNoPromotionBenefit(int num) { + return num % getPromotionCount(); + } + + public int getPromotionCount() { + return promotionPolicy.getPromotionCount(); + } + + public int getPromotionBuyCount() { + return promotionPolicy.getPromotionBuyCount(); + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getQuantity() { + return quantity; + } + + public String getPromotion() { + return promotion; + } +}
Java
ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ์ด ๋˜์—ˆ๋‚˜๋ผ๋Š” ์งˆ๋ฌธ์ด๋‹ˆ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ธ์ง€ ํ™•์ธํ•˜๋Š” ๋ถ€๋ถ„๋„ ์žˆ์œผ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,86 @@ +package store.model; + +import java.util.List; + +public class Products { + public static final int HAVE_PROMOTION_BENEFIT_SIZE = 2; + public static final int HAVE_NO_PROMOTION_BENEFIT_SIZE = 1; + List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public boolean isGetOneFree(Order order) { + Product promotion = getPromotionProduct(); + return isPromotionPeriod() && + isPromotionMoreThanOrder(order, promotion) && + isPromotionBenefitPossibleLeft(order, promotion) && + isPromotionStockEnough(order, promotion); + } + + public boolean isBuyOriginalPrice(Order order) { + return countBuyOriginalPrice(order) > 0; + } + + public boolean isPromotionPeriod() { + Product promotion = getPromotionProduct(); + return promotion.isPromotionPeriod(); + } + + private boolean isPromotionMoreThanOrder(Order order, Product promotion) { + return promotion.getQuantity() > order.getQuantity(); + } + + private boolean isPromotionBenefitPossibleLeft(Order order, Product promotion) { + return promotion.isPromotionBenefitPossibleLeft(order); + } + + private boolean isPromotionStockEnough(Order order, Product promotion) { + return promotion.getQuantity() >= order.getQuantity() + 1; + } + + public int countBuyOriginalPrice(Order order) { + Product promotion = getPromotionProduct(); + if (promotion.isPromotionPeriod() && !isPromotionMoreThanOrder(order, promotion)) { + return promotion.getNoPromotionBenefit(promotion.getQuantity()) + order.getQuantity() - promotion.getQuantity(); + } + return 0; + } + + public int countReducePromotionWhen(Order order) { + return order.getQuantity() - countBuyOriginalPrice(order); + } + + public void doNotOrderOriginalPrice(Order order) { + order.decreaseQuantity(countBuyOriginalPrice(order)); + } + + public boolean isOrderQuantityBuyOnlyPromotionStock(Order order) { + return countBuyOriginalPrice(order) == order.getQuantity(); + } + + public Product getPromotionProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return new Product(getNormalProduct().getName() + "," + getNormalProduct().getPrice() + ",0,null"); + } + throw new IllegalArgumentException(); + } + + public Product getNormalProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(1); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + throw new IllegalArgumentException(); + } + + public List<Product> getProducts() { + return products; + } +}
Java
```suggestion return promotion.getQuantity() > order.getQuantity(); ``` ์ด๋ ‡๊ฒŒ ๋ฐ”๊พธ์‹œ๋Š” ๊ฒƒ์ด ๋” ๋‚˜์„๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,86 @@ +package store.model; + +import java.util.List; + +public class Products { + public static final int HAVE_PROMOTION_BENEFIT_SIZE = 2; + public static final int HAVE_NO_PROMOTION_BENEFIT_SIZE = 1; + List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public boolean isGetOneFree(Order order) { + Product promotion = getPromotionProduct(); + return isPromotionPeriod() && + isPromotionMoreThanOrder(order, promotion) && + isPromotionBenefitPossibleLeft(order, promotion) && + isPromotionStockEnough(order, promotion); + } + + public boolean isBuyOriginalPrice(Order order) { + return countBuyOriginalPrice(order) > 0; + } + + public boolean isPromotionPeriod() { + Product promotion = getPromotionProduct(); + return promotion.isPromotionPeriod(); + } + + private boolean isPromotionMoreThanOrder(Order order, Product promotion) { + return promotion.getQuantity() > order.getQuantity(); + } + + private boolean isPromotionBenefitPossibleLeft(Order order, Product promotion) { + return promotion.isPromotionBenefitPossibleLeft(order); + } + + private boolean isPromotionStockEnough(Order order, Product promotion) { + return promotion.getQuantity() >= order.getQuantity() + 1; + } + + public int countBuyOriginalPrice(Order order) { + Product promotion = getPromotionProduct(); + if (promotion.isPromotionPeriod() && !isPromotionMoreThanOrder(order, promotion)) { + return promotion.getNoPromotionBenefit(promotion.getQuantity()) + order.getQuantity() - promotion.getQuantity(); + } + return 0; + } + + public int countReducePromotionWhen(Order order) { + return order.getQuantity() - countBuyOriginalPrice(order); + } + + public void doNotOrderOriginalPrice(Order order) { + order.decreaseQuantity(countBuyOriginalPrice(order)); + } + + public boolean isOrderQuantityBuyOnlyPromotionStock(Order order) { + return countBuyOriginalPrice(order) == order.getQuantity(); + } + + public Product getPromotionProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return new Product(getNormalProduct().getName() + "," + getNormalProduct().getPrice() + ",0,null"); + } + throw new IllegalArgumentException(); + } + + public Product getNormalProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(1); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + throw new IllegalArgumentException(); + } + + public List<Product> getProducts() { + return products; + } +}
Java
์ƒˆ๋กœ์šด ํด๋ž˜์Šค๋ฅผ ํ†ตํ•ด ํ•ด๋‹น ๋ถ€๋ถ„์„ ๋ฉ”์„œ๋“œ๋กœ ๋งŒ๋“ ๋‹ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,86 @@ +package store.model; + +import java.util.List; + +public class Products { + public static final int HAVE_PROMOTION_BENEFIT_SIZE = 2; + public static final int HAVE_NO_PROMOTION_BENEFIT_SIZE = 1; + List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public boolean isGetOneFree(Order order) { + Product promotion = getPromotionProduct(); + return isPromotionPeriod() && + isPromotionMoreThanOrder(order, promotion) && + isPromotionBenefitPossibleLeft(order, promotion) && + isPromotionStockEnough(order, promotion); + } + + public boolean isBuyOriginalPrice(Order order) { + return countBuyOriginalPrice(order) > 0; + } + + public boolean isPromotionPeriod() { + Product promotion = getPromotionProduct(); + return promotion.isPromotionPeriod(); + } + + private boolean isPromotionMoreThanOrder(Order order, Product promotion) { + return promotion.getQuantity() > order.getQuantity(); + } + + private boolean isPromotionBenefitPossibleLeft(Order order, Product promotion) { + return promotion.isPromotionBenefitPossibleLeft(order); + } + + private boolean isPromotionStockEnough(Order order, Product promotion) { + return promotion.getQuantity() >= order.getQuantity() + 1; + } + + public int countBuyOriginalPrice(Order order) { + Product promotion = getPromotionProduct(); + if (promotion.isPromotionPeriod() && !isPromotionMoreThanOrder(order, promotion)) { + return promotion.getNoPromotionBenefit(promotion.getQuantity()) + order.getQuantity() - promotion.getQuantity(); + } + return 0; + } + + public int countReducePromotionWhen(Order order) { + return order.getQuantity() - countBuyOriginalPrice(order); + } + + public void doNotOrderOriginalPrice(Order order) { + order.decreaseQuantity(countBuyOriginalPrice(order)); + } + + public boolean isOrderQuantityBuyOnlyPromotionStock(Order order) { + return countBuyOriginalPrice(order) == order.getQuantity(); + } + + public Product getPromotionProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return new Product(getNormalProduct().getName() + "," + getNormalProduct().getPrice() + ",0,null"); + } + throw new IllegalArgumentException(); + } + + public Product getNormalProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(1); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + throw new IllegalArgumentException(); + } + + public List<Product> getProducts() { + return products; + } +}
Java
์ƒˆ๋กœ์šด ์ƒ์„ฑ์ž๋ฅผ ๋งŒ๋“ค์–ด ์ฒ˜๋ฆฌํ•œ๋‹ค๋ฉด ์ด๋Ÿฐ ์ž‘์—…์ด ํ•„์š” ์—†์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,86 @@ +package store.model; + +import java.util.List; + +public class Products { + public static final int HAVE_PROMOTION_BENEFIT_SIZE = 2; + public static final int HAVE_NO_PROMOTION_BENEFIT_SIZE = 1; + List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public boolean isGetOneFree(Order order) { + Product promotion = getPromotionProduct(); + return isPromotionPeriod() && + isPromotionMoreThanOrder(order, promotion) && + isPromotionBenefitPossibleLeft(order, promotion) && + isPromotionStockEnough(order, promotion); + } + + public boolean isBuyOriginalPrice(Order order) { + return countBuyOriginalPrice(order) > 0; + } + + public boolean isPromotionPeriod() { + Product promotion = getPromotionProduct(); + return promotion.isPromotionPeriod(); + } + + private boolean isPromotionMoreThanOrder(Order order, Product promotion) { + return promotion.getQuantity() > order.getQuantity(); + } + + private boolean isPromotionBenefitPossibleLeft(Order order, Product promotion) { + return promotion.isPromotionBenefitPossibleLeft(order); + } + + private boolean isPromotionStockEnough(Order order, Product promotion) { + return promotion.getQuantity() >= order.getQuantity() + 1; + } + + public int countBuyOriginalPrice(Order order) { + Product promotion = getPromotionProduct(); + if (promotion.isPromotionPeriod() && !isPromotionMoreThanOrder(order, promotion)) { + return promotion.getNoPromotionBenefit(promotion.getQuantity()) + order.getQuantity() - promotion.getQuantity(); + } + return 0; + } + + public int countReducePromotionWhen(Order order) { + return order.getQuantity() - countBuyOriginalPrice(order); + } + + public void doNotOrderOriginalPrice(Order order) { + order.decreaseQuantity(countBuyOriginalPrice(order)); + } + + public boolean isOrderQuantityBuyOnlyPromotionStock(Order order) { + return countBuyOriginalPrice(order) == order.getQuantity(); + } + + public Product getPromotionProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return new Product(getNormalProduct().getName() + "," + getNormalProduct().getPrice() + ",0,null"); + } + throw new IllegalArgumentException(); + } + + public Product getNormalProduct() { + if (products.size() == HAVE_PROMOTION_BENEFIT_SIZE) { + return products.get(1); + } + if (products.size() == HAVE_NO_PROMOTION_BENEFIT_SIZE) { + return products.get(0); + } + throw new IllegalArgumentException(); + } + + public List<Product> getProducts() { + return products; + } +}
Java
1, 0์— ํ•ด๋‹นํ•˜๋Š” ์ธ๋ฑ์Šค๊ฐ€ ์–ด๋–ค ์ œํ’ˆ์˜ ์ธ๋ฑ์Šค์ธ์ง€ ํ‘œ์‹œํ•  ์ƒ์ˆ˜๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,60 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; +import store.util.Reader; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +public class PromotionPolicy { + private int promotionBuyCount; + private int promotionGetCount; + private String startDate; + private String endDate; + + public PromotionPolicy(String productPromotion) { + promotionBuyCount = 0; + promotionGetCount = 0; + startDate = "9999-12-31"; + endDate = "9999-12-31"; + initPromotionInfo(productPromotion); + } + + private void initPromotionInfo(String productPromotion) { + Reader reader = new Reader(); + List<String> lines = reader.readLines("src/main/resources/promotions.md").stream().skip(1).toList(); + lines.forEach(line -> updatePolicy(line, productPromotion)); + } + + private void updatePolicy(String line, String productPromotion) { + String[] promotionInfo = line.split(","); + String promotionName = promotionInfo[0]; + if (promotionName.equals(productPromotion)) { + promotionBuyCount = Integer.parseInt(promotionInfo[1]); + promotionGetCount = Integer.parseInt(promotionInfo[2]); + startDate = promotionInfo[3]; + endDate = promotionInfo[4]; + } + } + + public boolean isValidPeriod() { + LocalDateTime targetTime = DateTimes.now(); + + String[] startInfo = startDate.split("-"); + String[] endInfo = endDate.split("-"); + + LocalDate targetDate = LocalDate.of(targetTime.getYear(), targetTime.getMonth(), targetTime.getDayOfMonth()); + LocalDate startDate = LocalDate.of(Integer.parseInt(startInfo[0]), Integer.parseInt(startInfo[1]), Integer.parseInt(startInfo[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(endInfo[0]), Integer.parseInt(endInfo[1]), Integer.parseInt(endInfo[2])); + return !targetDate.isBefore(startDate) && !targetDate.isAfter(endDate); + } + + public int getPromotionCount() { + return promotionBuyCount + promotionGetCount; + } + + public int getPromotionBuyCount() { + return promotionBuyCount; + } +}
Java
LocalDate.parse()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋” ์‰ฝ๊ฒŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์œผ๋‹ˆ ์ด๋ฅผ ์ฐธ๊ณ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,113 @@ +package store.model; + +import store.constant.ProductState; +import store.exception.InvalidNonExistOrder; +import store.strategy.*; +import store.strategy.PromotionPeriod.BuyOriginalPrice; +import store.strategy.PromotionPeriod.GetOneFree; +import store.strategy.PromotionPeriod.NothingToAsk; + +import java.util.LinkedHashMap; + +public class Store { + private final LinkedHashMap<String, Products> storeProducts; + private final Receipt receipt; + + public Store() { + storeProducts = new LinkedHashMap<>(); + receipt = new Receipt(); + } + + public void calculateOrder(Order order, StockManager stockManager, boolean answer) { + Products products = getProducts(order.getName()); + Product normal = products.getNormalProduct(); + Product promotion = products.getPromotionProduct(); + int reduceNormal = stockManager.calculateNormalReduction(order, products, answer); + int reducePromotion = stockManager.calculatePromotionReduction(order, products, answer); + + reduceStock(normal, reduceNormal); + reduceStock(promotion, reducePromotion); + receipt.updateTotalAndDiscount(order, normal, stockManager.getCanGetDiscount()); + receipt.updateGiftProducts(promotion, reducePromotion); + } + + public boolean executeWhenNotPromotionPeriod(Order order) { + Products products = getProducts(order.getName()); + if (products.isPromotionPeriod()) { + return false; + } + calculateOrder(order, new NotPromotionPeriod(), true); + return true; + } + + public ProductState getProductState(Order order) { + if (executeWhenNotPromotionPeriod(order)) { + return ProductState.NO_PROMOTION_PERIOD; + } + if (checkGetOneFree(order)) { + return ProductState.GET_ONE_FREE; + } + if (checkBuyOriginalPrice(order)) { + return ProductState.BUY_ORIGINAL_PRICE; + } + return ProductState.NOTHING_TO_ASK; + } + + public boolean checkGetOneFree(Order order) { + Products products = getProducts(order.getName()); + return products.isGetOneFree(order); + } + + public void calculateWhenGetOneFreeCase(Order order, boolean isGetFree) { + calculateOrder(order, new GetOneFree(), isGetFree); + } + + public boolean checkBuyOriginalPrice(Order order) { + Products products = getProducts(order.getName()); + return products.isBuyOriginalPrice(order); + } + + public void calculateWhenBuyOriginalPrice(Order order, boolean getOriginalPrice) { + Products products = getProducts(order.getName()); + calculateOrder(order, new BuyOriginalPrice(order, products), getOriginalPrice); + } + + public void calculateWhenNothingToAsk(Order order) { + calculateOrder(order, new NothingToAsk(), true); + } + + public Receipt getReceipt(boolean isGetDiscount) { + if (!isGetDiscount) { + receipt.getNoMembershipDiscount(); + } + return receipt; + } + + public int countBuyOriginalPrice(Order order) { + Products products = getProducts(order.getName()); + return products.countBuyOriginalPrice(order); + } + + private void reduceStock(Product product, int countReduce) { + product.reduceStock(countReduce); + } + + public void addProduct(String name, Products products) { + storeProducts.put(name, products); + } + + public LinkedHashMap<String, Products> getStoreProducts() { + return storeProducts; + } + + public Products getParticularStoreProducts(String name) { + if (storeProducts.get(name) == null) { + throw new InvalidNonExistOrder(); + } + return storeProducts.get(name); + } + + public Products getProducts(String name) { + return storeProducts.get(name); + } +}
Java
์ด ๋ฉ”์„œ๋“œ๋Š” ์™ธ๋ถ€์—์„œ ์‹คํ–‰๋„ ๋˜์ง€์•Š์•„ private์„ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋” ๋‚˜์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ private์˜ ๊ฒฝ์šฐ ์‚ฌ์šฉ๋˜๋Š” public ๋ฐ‘์— ์œ„์น˜์‹œํ‚ค๋ฉด ์ฝ๊ธฐ์— ๋” ํŽธํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package store.strategy.PromotionPeriod; + +import store.model.Order; +import store.model.Product; +import store.model.Products; +import store.strategy.StockManager; + +public class BuyOriginalPrice implements StockManager { + private final boolean canGetDiscount; + + public BuyOriginalPrice(Order order, Products products) { + this.canGetDiscount = products.isOrderQuantityBuyOnlyPromotionStock(order); + } + + @Override + public int calculateNormalReduction(Order order, Products products, boolean getOriginalPrice) { + Product promotion = products.getPromotionProduct(); + + int reduceNormal = 0; + if (promotion.getQuantity() < order.getQuantity()) { + reduceNormal = order.getQuantity() - promotion.getQuantity(); + } + if (!getOriginalPrice) { + reduceNormal = 0; + } + return reduceNormal; + } + + @Override + public int calculatePromotionReduction(Order order, Products products, boolean getOriginalPrice) { + Product promotion = products.getPromotionProduct(); + + int reducePromotion = promotion.getQuantity(); + if (!getOriginalPrice) { + reducePromotion = products.countReducePromotionWhen(order); + products.doNotOrderOriginalPrice(order); + } + return reducePromotion; + } + + @Override + public boolean getCanGetDiscount() { + return canGetDiscount; + } +}
Java
์ด๋ ‡๊ฒŒ ์—ฌ๋Ÿฌ๊ฐ€์ง€๋กœ ๋ถ„๋ฅ˜๋˜๋Š” ๊ฒƒ์ด๋ผ๋ฉด ์ƒ์†๋„ ์ข‹์ง€๋งŒ enum์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,15 @@ +package store.util; + +public interface Task<T> { + static <T> T repeatUntilValid(Task<T> task) { + while (true) { + try { + return task.run(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + T run(); +}
Java
์ด๊ฒŒ ๋ฐ˜๋ณตํ•˜๋Š” ๋ถ€๋ถ„์ด์˜€๋„ค์š” Supplier๋ฅผ ์‚ฌ์šฉํ•˜์‹ ๋‹ค๋ฉด ๋” ํŽธํ•˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,67 @@ +package store.product.controller; + +import java.util.ArrayList; +import java.util.List; +import store.error.ErrorMessage; +import store.product.domain.PurchaseProduct; +import store.product.dto.PurchaseProductRequest; +import store.product.service.ProductService; +import store.product.view.ProductOutputView; +import store.state.PurchaseState; +import store.util.LoopTemplate; +import store.util.StringParser; +import store.util.StringValidator; +import store.view.InputView; + +public class ProductController { + + private final InputView inputView; + private final ProductOutputView outputView; + private final ProductService productService; + + public ProductController(final InputView inputView, final ProductOutputView outputView, + final ProductService productService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + } + + public void run() { + responseProductStatuses(); + final List<PurchaseProduct> purchaseProducts = requestPurchaseProduct(); + final PurchaseState purchaseState = PurchaseState.getInstance(); + purchaseState.updatePurchaseProducts(purchaseProducts); + } + + private void responseProductStatuses() { + outputView.printIntro(); + outputView.printProductStatus(productService.getProductStatuses()); + } + + private List<PurchaseProduct> requestPurchaseProduct() { + return LoopTemplate.tryCatchLoop(() -> { + outputView.printAskPurchaseProduct(); + final List<String> products = inputView.readProducts(); + final List<PurchaseProductRequest> purchaseProductRequests = generatePurchaseProductRequests(products); + return productService.generatePurchaseProducts(purchaseProductRequests); + }); + } + + private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> values) { + final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); + for (String value : values) { + StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); + final String product = StringParser.removePattern(value.trim(), "[\\[\\]]"); + purchaseProductRequests.add(createPurchaseProductRequest(product)); + } + return purchaseProductRequests; + } + + private PurchaseProductRequest createPurchaseProductRequest(final String product) { + final String[] splitProduct = product.split("-"); + final String name = splitProduct[0]; + final int quantity = StringParser.parseToNumber(splitProduct[1]); + return new PurchaseProductRequest(name, quantity); + } + +}
Java
### ๐. ์ปจํŠธ๋กค๋Ÿฌ์˜ ํ๋ฆ„ ์ œ์–ด๋ฅผ ์œ„ํ•ด PurchaseState๋ฅผ ๋„์ž…ํ•˜์‹  ๋ฐฐ๊ฒฝ์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ์ปจํŠธ๋กค๋Ÿฌ์˜ run() ๋ฉ”์„œ๋“œ๋“ค์ด ๋ฐ˜ํ™˜ ๊ฐ’ ์—†์ด void๋กœ ๋˜์–ด์žˆ๋”๋ผ๊ตฌ์š”. ๋Œ€์‹  PurchaseState๋ผ๋Š” ์‹ฑ๊ธ€ํ†ค์ด ๋งˆ์น˜ Repository์ฒ˜๋Ÿผ ๋™์ž‘ํ•˜๋ฉด์„œ ์ปจํŠธ๋กค๋Ÿฌ ๊ฐ„์˜ ํ๋ฆ„์„ ์ œ์–ดํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์‹ค์ œ Convenience ๊ฐ์ฒด์—์„œ๋Š” ์ด๋Ÿฐ ์‹์œผ๋กœ ๊ตฌํ˜„๋˜์–ด ์žˆ๋”๋ผ๊ตฌ์š”: ```java public void purchase() { do { productController.run(); promotionController.run(); paymentController.run(); } while (isRetryPurchase()); Console.close(); } private boolean isRetryPurchase() { return PurchaseState.getInstance().isRetryPurchase(); } ``` ์ด๋ ‡๊ฒŒ ๋ณด๋‹ˆ ๊ฐ ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ ๋…๋ฆฝ์ ์ธ ๋ชจ๋“ˆ์ฒ˜๋Ÿผ ์ž‘๋™ํ•˜๊ณ , ์ด ๋ชจ๋“ˆ๋“ค ์‚ฌ์ด์˜ ๋ฐ์ดํ„ฐ ํ๋ฆ„์„ PurchaseState๊ฐ€ ์ด์–ด์ฃผ๊ณ  ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š”. ์ด๋Ÿฐ ๊ตฌ์กฐ๋ฅผ ์ฑ„ํƒํ•˜์‹œ๊ฒŒ ๋œ ํŠน๋ณ„ํ•œ ๊ณ„๊ธฐ๋‚˜ ๊ณ ๋ฏผ์˜ ๊ณผ์ •์ด ์žˆ์œผ์…จ๋‚˜์š”? ์ฒ˜์Œ๋ถ€ํ„ฐ ์ด๋Ÿฐ ๊ตฌ์กฐ๋ฅผ ๊ณ„ํšํ•˜์‹  ๊ฑด์ง€, ์•„๋‹ˆ๋ฉด ๊ฐœ๋ฐœ ๊ณผ์ •์—์„œ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋ฐœ์ „๋œ ๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ๐Ÿ’ญ ์ €์˜€๋‹ค๋ฉด Controller์—์„œ ์‘๋‹ต์„ ๋ฐ˜ํ™˜ํ•˜๊ณ , ๋‹ค๋ฅธ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ๊ทธ ์‘๋‹ต๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์š”์ฒญ์„ ์‹œ์ž‘ํ•  ๊ฒƒ ๊ฐ™๊ฑฐ๋“ ์š”. ํ•˜์ง€๋งŒ ๋‹จ์ ์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ํ๋ฆ„์ œ์–ด์˜ ๋ถ€๋‹ด์ด ์ปค์ง€๊ธฐ๋„ ํ•˜๊ณ , ์–ด์ฉŒ๋ฉด ์ฝ”๋“œ๋ฅผ ๋ฆฌํŒฉํ† ๋ง ํ•ด์•ผ ํ•˜๋Š” ์œ„ํ—˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์žฅ์ ์ด๋ผ ํ•˜๋ฉด ์ €๋Š” ๊ทธ์ € ๊ฐ์ฒด์ง€ํ–ฅ์ ์ด๋‹ค..? ๋ผ๊ณ  ๋ฐ–์— ์ƒ๊ฐ์ด ์•ˆ๋“ค๊ฑฐ๋“ ์š”.. ์ฆ‰, ์ €๋„ ์–ด๋–ค๊ฒŒ ์ข‹์€์ง€ ์ž˜ ๋ชจ๋ฅด๊ณ  ์žˆ์–ด์š”. ์™œ ์ด๊ฑธ ์จ์•ผ๋งŒ ํ•˜๋Š”์ง€ ์ •ํ™•ํ•œ ์ด์œ ๋ฅผ์š”..! ๊ทธ๋ž˜์„œ ์ด๋ ‡๊ฒŒ ๋งŒ๋“œ์‹  ์ด์œ ๋ฅผ ์ œ๊ฐ€ ๋”์šฑ๋” ๊ถ๊ธˆํ•ด ํ•˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿฅน ---- ์ถ”๊ฐ€ ๋‚ด์šฉ: ์ด์–ด์„œ ์ฝ”๋“œ๋ฅผ ์ฝ๋‹ค๋ณด๋‹ˆ ๊ตฌ๋งค์ž์—๊ฒŒ ์ƒํ’๋ชฉ๋ก์„ ๋ณด์—ฌ์ค„๋•Œ ์ด๋•Œ, ProductStatus๊ฐ€ ์กฐํšŒ์šฉ DTO ์—ญํ• ๋„ ํ•˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ``` java public List<ProductStatus> getProductStatuses() { final List<ProductStatus> productStatuses = new ArrayList<>(); final List<Product> products = productRepository.findAll(); for (Product product : products) { final ProductStatus productStatus = ProductStatus.of(product); productStatuses.add(productStatus); addNormalProduct(product, productStatuses); } return productStatuses; } ``` ์‚ฌ์‹ค์ƒ ProductStatus๊ฐ€ DTO ์‘๋‹ต ๊ฐ์ฒด ์—ญํ• ์„ ํ•˜๊ณ  ์žˆ์—ˆ๊ตฐ์š”. ํ•˜์ง€๋งŒ ์‹ฑ๊ธ€ํ†ค ์ €์žฅ ๊ธฐ๋Šฅ์„ ๊ณ๋“ค์ธ. ์ด์ œ์•ผ ์™œ ์ด๋ ‡๊ฒŒ ์งœ์…จ๋Š”์ง€ ์ดํ•ด๊ฐ€ ๊ฐ€๋„ค์š”. ํ˜น์‹œ ์—ฌ๊ธฐ์— ๋” ์ˆ˜๋‹ฌ๋‹˜์˜ ์˜๊ฒฌ์ด ์žˆ์œผ์‹ ์ง€ ์—ฌ์ญค๋ณด๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,67 @@ +package store.product.controller; + +import java.util.ArrayList; +import java.util.List; +import store.error.ErrorMessage; +import store.product.domain.PurchaseProduct; +import store.product.dto.PurchaseProductRequest; +import store.product.service.ProductService; +import store.product.view.ProductOutputView; +import store.state.PurchaseState; +import store.util.LoopTemplate; +import store.util.StringParser; +import store.util.StringValidator; +import store.view.InputView; + +public class ProductController { + + private final InputView inputView; + private final ProductOutputView outputView; + private final ProductService productService; + + public ProductController(final InputView inputView, final ProductOutputView outputView, + final ProductService productService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + } + + public void run() { + responseProductStatuses(); + final List<PurchaseProduct> purchaseProducts = requestPurchaseProduct(); + final PurchaseState purchaseState = PurchaseState.getInstance(); + purchaseState.updatePurchaseProducts(purchaseProducts); + } + + private void responseProductStatuses() { + outputView.printIntro(); + outputView.printProductStatus(productService.getProductStatuses()); + } + + private List<PurchaseProduct> requestPurchaseProduct() { + return LoopTemplate.tryCatchLoop(() -> { + outputView.printAskPurchaseProduct(); + final List<String> products = inputView.readProducts(); + final List<PurchaseProductRequest> purchaseProductRequests = generatePurchaseProductRequests(products); + return productService.generatePurchaseProducts(purchaseProductRequests); + }); + } + + private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> values) { + final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); + for (String value : values) { + StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); + final String product = StringParser.removePattern(value.trim(), "[\\[\\]]"); + purchaseProductRequests.add(createPurchaseProductRequest(product)); + } + return purchaseProductRequests; + } + + private PurchaseProductRequest createPurchaseProductRequest(final String product) { + final String[] splitProduct = product.split("-"); + final String name = splitProduct[0]; + final int quantity = StringParser.parseToNumber(splitProduct[1]); + return new PurchaseProductRequest(name, quantity); + } + +}
Java
#### ๐Ÿ“š ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค. ๐Ÿฆฆ ์ข‹์€ ์ฝ”๋“œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! try - catch ๊ตฌ์กฐ๋ฅผ ํ…œํ”Œ๋ฆฟ ํŒจํ„ด์œผ๋กœ ์ •ํ˜•ํ™” ํ•œ ๋ฐฉ์‹ ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ด๋ฒˆ์— ์ด ๊ตฌ์กฐ๋ฅผ ๊ณต๋ถ€ํ•˜๊ณ  ์ ์šฉํ•ด์„œ ์ตœ์ข…์ฝ”ํ…Œ์— ์ ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๊ณ  ์‹ถ์€ ๋งˆ์Œ์ด ๋ฟœ๋ฟœ๋“ค์–ด์š” ใ…‹ใ…‹ ๊ทธ๋ฆฌ๊ณ  ์ข€ ์—ฌ๊ธฐ์„œ ๋” ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ๋Š”์ง€๋„ ์ฐพ์•„๋ณด๊ณ  ์‹ถ๋„ค์š”.
@@ -0,0 +1,67 @@ +package store.product.controller; + +import java.util.ArrayList; +import java.util.List; +import store.error.ErrorMessage; +import store.product.domain.PurchaseProduct; +import store.product.dto.PurchaseProductRequest; +import store.product.service.ProductService; +import store.product.view.ProductOutputView; +import store.state.PurchaseState; +import store.util.LoopTemplate; +import store.util.StringParser; +import store.util.StringValidator; +import store.view.InputView; + +public class ProductController { + + private final InputView inputView; + private final ProductOutputView outputView; + private final ProductService productService; + + public ProductController(final InputView inputView, final ProductOutputView outputView, + final ProductService productService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + } + + public void run() { + responseProductStatuses(); + final List<PurchaseProduct> purchaseProducts = requestPurchaseProduct(); + final PurchaseState purchaseState = PurchaseState.getInstance(); + purchaseState.updatePurchaseProducts(purchaseProducts); + } + + private void responseProductStatuses() { + outputView.printIntro(); + outputView.printProductStatus(productService.getProductStatuses()); + } + + private List<PurchaseProduct> requestPurchaseProduct() { + return LoopTemplate.tryCatchLoop(() -> { + outputView.printAskPurchaseProduct(); + final List<String> products = inputView.readProducts(); + final List<PurchaseProductRequest> purchaseProductRequests = generatePurchaseProductRequests(products); + return productService.generatePurchaseProducts(purchaseProductRequests); + }); + } + + private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> values) { + final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); + for (String value : values) { + StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); + final String product = StringParser.removePattern(value.trim(), "[\\[\\]]"); + purchaseProductRequests.add(createPurchaseProductRequest(product)); + } + return purchaseProductRequests; + } + + private PurchaseProductRequest createPurchaseProductRequest(final String product) { + final String[] splitProduct = product.split("-"); + final String name = splitProduct[0]; + final int quantity = StringParser.parseToNumber(splitProduct[1]); + return new PurchaseProductRequest(name, quantity); + } + +}
Java
#### ๐Ÿ“š ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค. ๐Ÿฆฆ ์ข‹์€ ์ฝ”๋“œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! [ ] ์„ ์ง€์šธ ๋•Œ replaceAll ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์—ˆ๊ตฐ์š”.. ์ด๊ฒƒ๋„ ๋ฉ”๋ชจํ•ด ๋‘ฌ์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค ๐Ÿ˜„ ---- ๋ณด์—ฌ์ฃผ๊ธฐ ๋ถ€๋„๋Ÿฌ์šด ์ €์˜ ์ฝ”๋“œ : ```java private String extractContentFromBrackets(final String input) { return input.substring(1, input.length() - 1); }```
@@ -0,0 +1,68 @@ +package store.product.domain; + +import java.util.Objects; +import store.promotion.domain.Promotion; + +public class Product { + + private static final String BLANK = ""; + private static final int ZERO = 0; + private final long id; + private final ProductInfo productInfo; + private int quantity; + + public Product(final Long id, final ProductInfo productInfo, final int quantity) { + this.id = id; + this.productInfo = productInfo; + this.quantity = quantity; + } + + public Long getId() { + return this.id; + } + + public void updateQuantity(final int quantity) { + this.quantity = quantity; + } + + public String getPromotionName() { + final Promotion promotion = productInfo.promotion(); + if (Objects.equals(promotion, null)) { + return BLANK; + } + return promotion.getPromotionName(); + } + + public boolean canReceiveMorePromotion(final int quantity) { + return productInfo.promotion().canPromotion(quantity); + } + + + public int calculateRemainingQuantity(final int quantity) { + final Promotion promotion = productInfo.promotion(); + if (!Objects.equals(promotion, null)) { + return promotion.getRemainingQuantity(quantity); + } + return ZERO; + } + + public int getBuyQuantity() { + return productInfo.promotion().getBuy(); + } + + public int getPrice() { + return productInfo.price(); + } + + public String getName() { + return productInfo.name(); + } + + public Promotion getPromotion() { + return productInfo.promotion(); + } + + public int getQuantity() { + return quantity; + } +}
Java
### ๐. Product ๋„๋ฉ”์ธ์˜ ์„ค๊ณ„ ๊ณผ์ •์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. #### ์งˆ๋ฌธ์˜๋„: ์ด๋ฒˆ์— ํ”„๋ฅด๋ชจ์…˜ ํ• ์ธ ๋•Œ๋ฌธ์— Product์™€ Promotion์€ ๊ฐœ์ธ์ ์œผ๋กœ ์„œ๋กœ๊ฐ€ ํ•„์š”ํ•œ ๊ด€๊ณ„์ฒ˜๋Ÿผ ๋А๊ปด์กŒ์—ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ œ๊ฒ ๋„๋ฉ”์ธ ์„ค๊ณ„๊ฐ€ ํฐ ๊ณผ์ œ์˜€์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ด๋ ‡๊ฒŒ ๊ตฌ์ƒํ•˜์‹œ๊ฒŒ ๋œ ์ด์œ ๋ฅผ ๋“ค์–ด๋ณด๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค. ๐Ÿฅน ์•„๋ž˜ ์‚ฌ์ง„์€ ์ˆ˜๋‹ฌ๋‹˜์ด ์ฒ˜์Œ ์„ค๊ณ„ํ•˜์…จ๋˜ Product, ์ดํ›„ ์ตœ์ข… ์ˆ˜์ •๋œ Product ์ž…๋‹ˆ๋‹ค. <img width="1188" alt="image" src="https://github.com/user-attachments/assets/d87d75f0-6788-46c9-bc8b-836599692032">
@@ -0,0 +1,42 @@ +package store.product.domain; + +public class ProductQuantity { + + private int normalQuantity; + private int promotionQuantity; + private int nonPromotionQuantity; + + public ProductQuantity(final int normalQuantity, final int promotionQuantity, final int nonPromotionQuantity) { + this.normalQuantity = normalQuantity; + this.promotionQuantity = promotionQuantity; + this.nonPromotionQuantity = nonPromotionQuantity; + } + + public int calculateTotalQuantity() { + return normalQuantity + promotionQuantity + nonPromotionQuantity; + } + + public int getNormalQuantity() { + return normalQuantity; + } + + public int getPromotionQuantity() { + return promotionQuantity; + } + + public int getNonPromotionQuantity() { + return nonPromotionQuantity; + } + + public void updateNormalQuantity(final int normalQuantity) { + this.normalQuantity = normalQuantity; + } + + public void updatePromotionQuantity(final int promotionQuantity) { + this.promotionQuantity = promotionQuantity; + } + + public void updateNonPromotionQuantity(final int nonPromotionQuantity) { + this.nonPromotionQuantity = nonPromotionQuantity; + } +}
Java
์ˆ˜๋Ÿ‰ ๊ฐ์ฒด๋ฅผ ๋ถˆ๋ณ€๊ฐ์ฒด๋กœ ๋งŒ๋“ค์–ด ๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ์˜ˆ์‹œ ```java public class ProductQuantity { private final int normalQuantity; // < -- final ์ถ”๊ฐ€ private final int promotionQuantity; // < -- final ์ถ”๊ฐ€ private final int nonPromotionQuantity; // < -- final ์ถ”๊ฐ€ public ProductQuantity(final int normalQuantity, final int promotionQuantity, final int nonPromotionQuantity) { this.normalQuantity = normalQuantity; this.promotionQuantity = promotionQuantity; this.nonPromotionQuantity = nonPromotionQuantity; } public ProductQuantity updateNormalQuantity(final int normalQuantity) { return new ProductQuantity(normalQuantity, // <-- ๋ณ€๊ฒฝ์‹œ ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ this.promotionQuantity, this.nonPromotionQuantity); } public ProductQuantity updatePromotionQuantity(final int promotionQuantity) { return new ProductQuantity(this.normalQuantity, promotionQuantity, this.nonPromotionQuantity); } ``` ## ์ˆ˜๋Ÿ‰์„ ๋ถˆ๋ณ€ ๊ฐ์ฒด๋กœ ํ–ˆ์„๋•Œ ์žฅ์  ### 1. ๊ฐ์ฒด ์ƒํƒœ ๋ณด์žฅ ์ด๋ฒˆ ๋ฏธ์…˜์—์„œ ์žฌ๊ณ  ์ƒํƒœ์˜ ์ตœ์‹ ํ™”๋ฅผ ํ•ญ์ƒ ๋ฐ˜์˜ํ•ด์•ผ ํ•˜๋Š” ๋งŒํผ, ๊ฐ์ฒด ์ƒํƒœ๊ฐ€ ์˜ˆ๊ธฐ์น˜ ์•Š๊ฒŒ ๋ณ€๊ฒฝ๋  ๊ฐ€๋Šฅ์„ฑ์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒƒ๋„ ์ƒ๊ฐํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ €๋Š” ์ˆ˜๋Ÿ‰ ๊ฐ์ฒด๋ฅผ ๋ถˆ๋ณ€ํƒ€์ž…์œผ๋กœ ์ง€์ • ํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค. ```java ProductQuantity original = new ProductQuantity(10, 5, 3); ProductQuantity modified = original.updateNormalQuantity(15); // ์›๋ณธ original ๊ฐ์ฒด๋Š” ๋ณ€๊ฒฝ๋˜์ง€ ์•Š์Œ ``` ### 2. ์œ ์ง€ ๋ณด์ˆ˜ํ–ฅ์ƒ ### ์ด์ „ ``` java ProducctQuantity original; original.updateNormalQuantity(3); original.updatePromotionQuantity(7); ``` ### ๋ฆฌํŒฉํ† ๋ง ํ›„ ```java ProductQuantity updated = original.updateNormalQuantity(15) .updatePromotionQuantity(8); ``` ### ์˜ˆ๋ฅผ ๋“ค์–ด PromotionService ์˜ ์ฝ”๋“œ์ค‘ ํ•˜๋‚˜๋ฅผ ์˜ˆ๋ฅผ ๋“ค๋ฉด ### ๋ณ€๊ฒฝ ์ „ <img width="547" alt="image" src="https://github.com/user-attachments/assets/5c0aa215-5d91-438e-a482-472c77ff9abd"> ### ๋ณ€๊ฒฝ ํ›„ <img width="667" alt="image" src="https://github.com/user-attachments/assets/5fb5a504-9f2d-4e8a-a72d-f500f98eb1e1">
@@ -0,0 +1,67 @@ +package store.product.controller; + +import java.util.ArrayList; +import java.util.List; +import store.error.ErrorMessage; +import store.product.domain.PurchaseProduct; +import store.product.dto.PurchaseProductRequest; +import store.product.service.ProductService; +import store.product.view.ProductOutputView; +import store.state.PurchaseState; +import store.util.LoopTemplate; +import store.util.StringParser; +import store.util.StringValidator; +import store.view.InputView; + +public class ProductController { + + private final InputView inputView; + private final ProductOutputView outputView; + private final ProductService productService; + + public ProductController(final InputView inputView, final ProductOutputView outputView, + final ProductService productService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + } + + public void run() { + responseProductStatuses(); + final List<PurchaseProduct> purchaseProducts = requestPurchaseProduct(); + final PurchaseState purchaseState = PurchaseState.getInstance(); + purchaseState.updatePurchaseProducts(purchaseProducts); + } + + private void responseProductStatuses() { + outputView.printIntro(); + outputView.printProductStatus(productService.getProductStatuses()); + } + + private List<PurchaseProduct> requestPurchaseProduct() { + return LoopTemplate.tryCatchLoop(() -> { + outputView.printAskPurchaseProduct(); + final List<String> products = inputView.readProducts(); + final List<PurchaseProductRequest> purchaseProductRequests = generatePurchaseProductRequests(products); + return productService.generatePurchaseProducts(purchaseProductRequests); + }); + } + + private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> values) { + final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); + for (String value : values) { + StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); + final String product = StringParser.removePattern(value.trim(), "[\\[\\]]"); + purchaseProductRequests.add(createPurchaseProductRequest(product)); + } + return purchaseProductRequests; + } + + private PurchaseProductRequest createPurchaseProductRequest(final String product) { + final String[] splitProduct = product.split("-"); + final String name = splitProduct[0]; + final int quantity = StringParser.parseToNumber(splitProduct[1]); + return new PurchaseProductRequest(name, quantity); + } + +}
Java
@plan11plan ์‹ฑ๊ธ€ํ†ค์„ ๋„์ž…ํ•˜๊ฒŒ ๋œ ๊ณผ์ •์€ ๋‹ค์Œ๊ณผ ๊ฐ™์•„์š”. > 1. 3๊ฐœ์˜ ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ ๋ชจ๋‘ ๋™์ผํ•œ ๋ฐ์ดํ„ฐ(List<PurchaseProduct>)๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์Œ > 2. ํ•ด๋‹น ๋ฐ์ดํ„ฐ๋ฅผ ๋งค๋ฒˆ ์ปจํŠธ๋กค๋Ÿฌ๋ผ๋ฆฌ ๋„˜๊ฒจ์ฃผ๋Š”๊ฒƒ ๋ณด๋‹ค ๋” ๋‚˜์€ ๋ฐฉ๋ฒ•์ด ์—†์„๊นŒ ๊ณ ๋ฏผํ•˜๊ฒŒ ๋จ > 3. ๊ทธ ๊ณผ์ • ์†์—์„œ ๋ฆฌ์•กํŠธ ๋ฆฌ๋•์Šค๋ฅผ ๋– ์˜ฌ๋ฆฌ๊ฒŒ ๋จ, ๊ทธ๋ž˜์„œ List<PurchaseProduct>์˜ ์ƒํƒœ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” PurchaseState ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋‘๊ฒŒ ๋จ > 4. PurchaseState๊ฐ€ ๊ด€๋ฆฌํ•˜๋Š” List<PurchaseProduct>์€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ „์—ญ์—์„œ ๋™์ผํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผํ•จ > 5. ๋”ฐ๋ผ์„œ PurchaseState์€ ๋‹จ ํ•˜๋‚˜์˜ ์ธ์Šคํ„ด์Šค๋งŒ ์กด์žฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ๊ตฌํ˜„ํ•˜๊ฒŒ ๋จ ํ•˜์ง€๋งŒ ์ด๋ ‡๊ฒŒ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ์ „์—ญ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ์‹ฑ๊ธ€ํ†ค ๊ฐ์ฒด์˜ ๊ฒฝ์šฐ ํ•„๋“œ์— ์ƒํƒœ๋ฅผ ๊ฐ€์ง€๋ฉด, ๋‚˜์ค‘์— ๋ฒ„๊ทธ๊ฐ€ ํ„ฐ์กŒ์„๋•Œ ๋””๋ฒ„๊น…ํ•˜๊ธฐ ํž˜๋“ค๋‹ค๋Š” ๋‹จ์ ๋„ ์กด์žฌํ•ด์š”! ๊ทธ๋ž˜์„œ ๋Œ์ด์ผœ๋ณด๋ฉด ์ด๋ ‡๊ฒŒ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ์ž‘์„ฑํ•ด์„œ ์ปจํŠธ๋กค๋Ÿฌ์˜ ์ฝ”๋“œ๋“ค์ด ์ด์˜๊ฒŒ ์ž‘์„ฑ์ด ๋์ง€๋งŒ, ์กฐ๊ธˆ์€ ์•„์‰ฌ์šด ์„ค๊ณ„๋ผ๊ณ  ์ƒ๊ฐ์ด ๋“œ๋„ค์š” ใ…Žใ…Ž --- ```java public List<ProductStatus> getProductStatuses() { final List<ProductStatus> productStatuses = new ArrayList<>(); final List<Product> products = productRepository.findAll(); for (Product product : products) { final ProductStatus productStatus = ProductStatus.of(product); productStatuses.add(productStatus); addNormalProduct(product, productStatuses); } return productStatuses; } ``` ๊ทธ๋ฆฌ๊ณ  ์งš์–ด์ฃผ์‹  ์š” ๋ถ€๋ถ„์€ PurchaseProduct๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—, ์‹ฑ๊ธ€ํ†ค ๊ฐ์ฒด์— ์ €์žฅํ•˜๋Š” ๋ถ€๋ถ„์ด ์—†์–ด์š” ์•„๋งˆ ์ œ๊ฐ€ ๋„ค์ด๋ฐ์„ ์ž˜๋ชปํ•ด์„œ ํ—ท๊ฐˆ๋ฆฌ์‹ ๊ฒƒ ๊ฐ™์•„์š” ใ…Žใ…Ž!
@@ -0,0 +1,67 @@ +package store.product.controller; + +import java.util.ArrayList; +import java.util.List; +import store.error.ErrorMessage; +import store.product.domain.PurchaseProduct; +import store.product.dto.PurchaseProductRequest; +import store.product.service.ProductService; +import store.product.view.ProductOutputView; +import store.state.PurchaseState; +import store.util.LoopTemplate; +import store.util.StringParser; +import store.util.StringValidator; +import store.view.InputView; + +public class ProductController { + + private final InputView inputView; + private final ProductOutputView outputView; + private final ProductService productService; + + public ProductController(final InputView inputView, final ProductOutputView outputView, + final ProductService productService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + } + + public void run() { + responseProductStatuses(); + final List<PurchaseProduct> purchaseProducts = requestPurchaseProduct(); + final PurchaseState purchaseState = PurchaseState.getInstance(); + purchaseState.updatePurchaseProducts(purchaseProducts); + } + + private void responseProductStatuses() { + outputView.printIntro(); + outputView.printProductStatus(productService.getProductStatuses()); + } + + private List<PurchaseProduct> requestPurchaseProduct() { + return LoopTemplate.tryCatchLoop(() -> { + outputView.printAskPurchaseProduct(); + final List<String> products = inputView.readProducts(); + final List<PurchaseProductRequest> purchaseProductRequests = generatePurchaseProductRequests(products); + return productService.generatePurchaseProducts(purchaseProductRequests); + }); + } + + private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> values) { + final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); + for (String value : values) { + StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); + final String product = StringParser.removePattern(value.trim(), "[\\[\\]]"); + purchaseProductRequests.add(createPurchaseProductRequest(product)); + } + return purchaseProductRequests; + } + + private PurchaseProductRequest createPurchaseProductRequest(final String product) { + final String[] splitProduct = product.split("-"); + final String name = splitProduct[0]; + final int quantity = StringParser.parseToNumber(splitProduct[1]); + return new PurchaseProductRequest(name, quantity); + } + +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค~ โ˜บ๏ธ
@@ -0,0 +1,67 @@ +package store.product.controller; + +import java.util.ArrayList; +import java.util.List; +import store.error.ErrorMessage; +import store.product.domain.PurchaseProduct; +import store.product.dto.PurchaseProductRequest; +import store.product.service.ProductService; +import store.product.view.ProductOutputView; +import store.state.PurchaseState; +import store.util.LoopTemplate; +import store.util.StringParser; +import store.util.StringValidator; +import store.view.InputView; + +public class ProductController { + + private final InputView inputView; + private final ProductOutputView outputView; + private final ProductService productService; + + public ProductController(final InputView inputView, final ProductOutputView outputView, + final ProductService productService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + } + + public void run() { + responseProductStatuses(); + final List<PurchaseProduct> purchaseProducts = requestPurchaseProduct(); + final PurchaseState purchaseState = PurchaseState.getInstance(); + purchaseState.updatePurchaseProducts(purchaseProducts); + } + + private void responseProductStatuses() { + outputView.printIntro(); + outputView.printProductStatus(productService.getProductStatuses()); + } + + private List<PurchaseProduct> requestPurchaseProduct() { + return LoopTemplate.tryCatchLoop(() -> { + outputView.printAskPurchaseProduct(); + final List<String> products = inputView.readProducts(); + final List<PurchaseProductRequest> purchaseProductRequests = generatePurchaseProductRequests(products); + return productService.generatePurchaseProducts(purchaseProductRequests); + }); + } + + private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> values) { + final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); + for (String value : values) { + StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); + final String product = StringParser.removePattern(value.trim(), "[\\[\\]]"); + purchaseProductRequests.add(createPurchaseProductRequest(product)); + } + return purchaseProductRequests; + } + + private PurchaseProductRequest createPurchaseProductRequest(final String product) { + final String[] splitProduct = product.split("-"); + final String name = splitProduct[0]; + final int quantity = StringParser.parseToNumber(splitProduct[1]); + return new PurchaseProductRequest(name, quantity); + } + +}
Java
@plan11plan replaceAll()์€ ์ •๊ทœ์‹์„ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์–‘ํ•œ ํŒจํ„ด์„ ๋ณ€ํ™˜ํ•˜๊ธฐ ์ข‹๋”๋ผ๊ตฌ์š” ใ…Žใ…Ž!
@@ -0,0 +1,68 @@ +package store.product.domain; + +import java.util.Objects; +import store.promotion.domain.Promotion; + +public class Product { + + private static final String BLANK = ""; + private static final int ZERO = 0; + private final long id; + private final ProductInfo productInfo; + private int quantity; + + public Product(final Long id, final ProductInfo productInfo, final int quantity) { + this.id = id; + this.productInfo = productInfo; + this.quantity = quantity; + } + + public Long getId() { + return this.id; + } + + public void updateQuantity(final int quantity) { + this.quantity = quantity; + } + + public String getPromotionName() { + final Promotion promotion = productInfo.promotion(); + if (Objects.equals(promotion, null)) { + return BLANK; + } + return promotion.getPromotionName(); + } + + public boolean canReceiveMorePromotion(final int quantity) { + return productInfo.promotion().canPromotion(quantity); + } + + + public int calculateRemainingQuantity(final int quantity) { + final Promotion promotion = productInfo.promotion(); + if (!Objects.equals(promotion, null)) { + return promotion.getRemainingQuantity(quantity); + } + return ZERO; + } + + public int getBuyQuantity() { + return productInfo.promotion().getBuy(); + } + + public int getPrice() { + return productInfo.price(); + } + + public String getName() { + return productInfo.name(); + } + + public Promotion getPromotion() { + return productInfo.promotion(); + } + + public int getQuantity() { + return quantity; + } +}
Java
@plan11plan ์ €๋Š” `product.md`, `promotion.md` ์ด ๋‘ ํŒŒ์ผ์ด ๋งˆ์น˜ ์ƒํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜์„ ์ €์žฅํ•˜๊ณ  ์žˆ๋Š” DB์ฒ˜๋Ÿผ ๋А๊ปด์กŒ๊ฑฐ๋“ ์š”. ๊ทธ๋ž˜์„œ ์ด ๋ฐ์ดํ„ฐ๋“ค๊ณผ ๋งคํ•‘ํ•  ์ˆ˜ ์žˆ๋Š” ์—”ํ‹ฐํ‹ฐ ๊ฐ์ฒด๊ฐ€ ํ•„์š”ํ•ด์„œ Product, Promotion ํด๋ž˜์Šค๋ฅผ ๋‘์—ˆ๊ณ , Product๋งŒ Promotion์„ ์ฐธ์กฐํ•˜๋Š” ๋‹จ๋ฐฉํ–ฅ ๋‹ค๋Œ€์ผ ๊ด€๊ณ„๋กœ ํ’€์–ด๋ƒˆ์–ด์š”~ ๊ทธ๋ฆฌ๊ณ  ๋‚˜์ค‘์— ๋ณด๋‹ˆ๊นŒ Product์˜ ํ•„๋“œ ์ˆ˜๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์•„์ ธ์„œ ์ผ๋ถ€๋Š” ProductInfo VO๋กœ ๋”ฐ๋กœ ๋นผ์„œ ๊ด€๋ฆฌ๋ฅผ ํ•˜๊ฒŒ๋” ํ–ˆ์–ด์š”~
@@ -0,0 +1,42 @@ +package store.product.domain; + +public class ProductQuantity { + + private int normalQuantity; + private int promotionQuantity; + private int nonPromotionQuantity; + + public ProductQuantity(final int normalQuantity, final int promotionQuantity, final int nonPromotionQuantity) { + this.normalQuantity = normalQuantity; + this.promotionQuantity = promotionQuantity; + this.nonPromotionQuantity = nonPromotionQuantity; + } + + public int calculateTotalQuantity() { + return normalQuantity + promotionQuantity + nonPromotionQuantity; + } + + public int getNormalQuantity() { + return normalQuantity; + } + + public int getPromotionQuantity() { + return promotionQuantity; + } + + public int getNonPromotionQuantity() { + return nonPromotionQuantity; + } + + public void updateNormalQuantity(final int normalQuantity) { + this.normalQuantity = normalQuantity; + } + + public void updatePromotionQuantity(final int promotionQuantity) { + this.promotionQuantity = promotionQuantity; + } + + public void updateNonPromotionQuantity(final int nonPromotionQuantity) { + this.nonPromotionQuantity = nonPromotionQuantity; + } +}
Java
@plan11plan ์•ˆ๊ทธ๋ž˜๋„ ์š”๋ถ€๋ถ„์€ ๋ถˆ๋ณ€์œผ๋กœ ๋ฆฌํŒฉํ† ๋ง ํ•ด์•ผ๊ฒ ๋‹ค ๋ผ๋Š” ์ƒ๊ฐ์€ ์žˆ์—ˆ๊ฑฐ๋“ ์š” ใ…Žใ…Ž! ์ด๊ฑฐ ์™ธ์—๋„ ๋ถˆ๋ณ€์œผ๋กœ ํ•ด์•ผํ•˜๋Š” ํฌ์ธํŠธ๋“ค์ด ๋ช‡๊ตฐ๋ฐ ๋” ์žˆ์–ด์„œ ํ•จ๊ป˜ ๋ฆฌํŒฉํ† ๋ง ํ•  ์˜ˆ์ •์ด์—์š”~!
@@ -0,0 +1,34 @@ +package store; + +import camp.nextstep.edu.missionutils.Console; +import store.payment.controller.PaymentController; +import store.product.controller.ProductController; +import store.promotion.controller.PromotionController; +import store.state.PurchaseState; + +public class Convenience { + + private final ProductController productController; + private final PromotionController promotionController; + private final PaymentController paymentController; + + public Convenience(final ProductController productController, final PromotionController promotionController, + final PaymentController paymentController) { + this.productController = productController; + this.promotionController = promotionController; + this.paymentController = paymentController; + } + + public void purchase() { + do { + productController.run(); + promotionController.run(); + paymentController.run(); + } while (isRetryPurchase()); + Console.close(); + } + + private boolean isRetryPurchase() { + return PurchaseState.getInstance().isRetryPurchase(); + } +}
Java
์‹ฑ๊ธ€ํ†ค์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ณ  ์‹ถ์–ด์„œ ์งˆ๋ฌธํ•ด์š”. ์ €๋Š” ์‹ฑ๊ธ€ํ†ค์„ ์œ ์ง€ํ•˜๋Š” ๊ฐ์ฒด๋Š” ๋™์‹œ์„ฑ ๋ฌธ์ œ ๋•Œ๋ฌธ์— ์ƒํƒœ๋ฅผ ๊ฐ–๋Š” ํ•„๋“œ๋ฅผ ์ง€์–‘ํ•ด์•ผ ํ•œ๋‹ค๊ณ  ์•Œ๊ณ  ์žˆ์–ด์š”. ๊ทธ๋Ÿฐ๋ฐ PurchaseState์˜ ๊ฒฝ์šฐ purchaseProducts์™€ isRetryPurchase์™€ ๊ฐ™์ด ์ƒํƒœ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ํ•„๋“œ๊ฐ€ ์กด์žฌํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. ์ด๋ ‡๊ฒŒ ์„ค๊ณ„ํ•˜์˜€์„ ๋•Œ ๋™์‹œ์„ฑ ๋ฌธ์ œ๋Š” ์ƒ๊ธฐ์ง€ ์•Š๋‚˜์š”? ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ์™œ ๊ทธ๋Ÿฐ ๊ฑด๊ฐ€์š”?
@@ -0,0 +1,106 @@ +package store.config; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; +import store.error.ErrorMessage; +import store.error.exception.InvalidFailInitialDataLoadException; +import store.product.domain.Product; +import store.product.domain.ProductInfo; +import store.product.domain.ProductRepository; +import store.promotion.domain.Promotion; +import store.promotion.domain.PromotionDateTime; +import store.promotion.domain.PromotionRepository; +import store.promotion.domain.PromotionType; +import store.util.StringParser; + +public class InitialDataLoader { + + private static final String PATH_PROMOTIONS = "promotions.md"; + private static final String PATH_PRODUCTS = "products.md"; + private static final String DELIMITER_COMMA = ","; + private final PromotionRepository promotionRepository; + private final ProductRepository productRepository; + private Long promotionSequence = 1L; + private Long productSequence = 1L; + + public InitialDataLoader(final PromotionRepository promotionRepository, final ProductRepository productRepository) { + this.promotionRepository = promotionRepository; + this.productRepository = productRepository; + } + + public void initialize() { + saveAllPromotions(); + saveAllProducts(); + } + + private void saveAllPromotions() { + final Queue<String> fileLines = readFileLines(PATH_PROMOTIONS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + savePromotion(line); + } + } + + + private void saveAllProducts() { + final Queue<String> fileLines = readFileLines(PATH_PRODUCTS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + saveProduct(line); + } + } + + private void saveProduct(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Long id = productSequence++; + final Product product = createProduct(id, tokens); + productRepository.save(id, product); + } + + private Product createProduct(final Long id, final List<String> tokens) { + final String promotionName = tokens.get(3); + final Promotion promotion = promotionRepository.findByPromotionType(PromotionType.findByName(promotionName)) + .orElse(null); + final int price = StringParser.parseToNumber(tokens.get(1)); + final int quantity = StringParser.parseToNumber(tokens.get(2)); + final ProductInfo productInfo = new ProductInfo(tokens.get(0), price, promotion); + return new Product(id, productInfo, quantity); + } + + + private void savePromotion(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Promotion promotion = createPromotion(tokens); + promotionRepository.save(promotionSequence++, promotion); + } + + private Promotion createPromotion(final List<String> tokens) { + final PromotionType type = PromotionType.findByName(tokens.get(0)); + final int buy = StringParser.parseToNumber(tokens.get(1)); + final int get = StringParser.parseToNumber(tokens.get(2)); + final PromotionDateTime promotionDateTime = new PromotionDateTime(tokens.get(3), tokens.get(4)); + return new Promotion(type, promotionDateTime, buy, get); + } + + + private Queue<String> readFileLines(final String path) { + try { + URI uri = getClass().getClassLoader().getResource(path).toURI(); + return new ArrayDeque<>(Files.readAllLines(Paths.get(uri))); + } catch (Exception e) { + throw new InvalidFailInitialDataLoadException(ErrorMessage.INVALID_FAIL_INITIAL_DATA_LOAD); + } + } +}
Java
p4 ```suggestion private static final String DELIMITER = ","; ``` ๊ตฌ๋ถ„์ž๋Š” ๋ณ€๊ฒฝ๊ฐ€๋Šฅ์„ฑ์ด ํฌ๋‹ค๊ณ  ์กฐ์‹ฌ์Šค๋Ÿฝ๊ฒŒ ์ƒ๊ฐํ•ด ๋ด…๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๊ตฌ๋ถ„์ž๊ฐ€ ๋ณ€๊ฒฝ๋œ๋‹ค๋ฉด ๋ณ€์ˆ˜ ์ด๋ฆ„๋„ ๋ณ€๊ฒฝํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ณ€๊ฒฝ์—๋„ ์œ ์—ฐํ•˜๊ฒŒ ๋Œ€์ฒ˜ํ•˜๊ธฐ ์œ„ํ•ด DELMITER๋กœ ๋ณ€์ˆ˜๋ช…์„ ๋ช…๋ช…ํ•˜๋Š” ๊ฒƒ๋„ ํ•˜๋‚˜์˜ ๋ฐฉ๋ฒ•์ด ๋ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๐Ÿ˜„
@@ -0,0 +1,106 @@ +package store.config; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; +import store.error.ErrorMessage; +import store.error.exception.InvalidFailInitialDataLoadException; +import store.product.domain.Product; +import store.product.domain.ProductInfo; +import store.product.domain.ProductRepository; +import store.promotion.domain.Promotion; +import store.promotion.domain.PromotionDateTime; +import store.promotion.domain.PromotionRepository; +import store.promotion.domain.PromotionType; +import store.util.StringParser; + +public class InitialDataLoader { + + private static final String PATH_PROMOTIONS = "promotions.md"; + private static final String PATH_PRODUCTS = "products.md"; + private static final String DELIMITER_COMMA = ","; + private final PromotionRepository promotionRepository; + private final ProductRepository productRepository; + private Long promotionSequence = 1L; + private Long productSequence = 1L; + + public InitialDataLoader(final PromotionRepository promotionRepository, final ProductRepository productRepository) { + this.promotionRepository = promotionRepository; + this.productRepository = productRepository; + } + + public void initialize() { + saveAllPromotions(); + saveAllProducts(); + } + + private void saveAllPromotions() { + final Queue<String> fileLines = readFileLines(PATH_PROMOTIONS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + savePromotion(line); + } + } + + + private void saveAllProducts() { + final Queue<String> fileLines = readFileLines(PATH_PRODUCTS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + saveProduct(line); + } + } + + private void saveProduct(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Long id = productSequence++; + final Product product = createProduct(id, tokens); + productRepository.save(id, product); + } + + private Product createProduct(final Long id, final List<String> tokens) { + final String promotionName = tokens.get(3); + final Promotion promotion = promotionRepository.findByPromotionType(PromotionType.findByName(promotionName)) + .orElse(null); + final int price = StringParser.parseToNumber(tokens.get(1)); + final int quantity = StringParser.parseToNumber(tokens.get(2)); + final ProductInfo productInfo = new ProductInfo(tokens.get(0), price, promotion); + return new Product(id, productInfo, quantity); + } + + + private void savePromotion(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Promotion promotion = createPromotion(tokens); + promotionRepository.save(promotionSequence++, promotion); + } + + private Promotion createPromotion(final List<String> tokens) { + final PromotionType type = PromotionType.findByName(tokens.get(0)); + final int buy = StringParser.parseToNumber(tokens.get(1)); + final int get = StringParser.parseToNumber(tokens.get(2)); + final PromotionDateTime promotionDateTime = new PromotionDateTime(tokens.get(3), tokens.get(4)); + return new Promotion(type, promotionDateTime, buy, get); + } + + + private Queue<String> readFileLines(final String path) { + try { + URI uri = getClass().getClassLoader().getResource(path).toURI(); + return new ArrayDeque<>(Files.readAllLines(Paths.get(uri))); + } catch (Exception e) { + throw new InvalidFailInitialDataLoadException(ErrorMessage.INVALID_FAIL_INITIAL_DATA_LOAD); + } + } +}
Java
wow `URI` ํƒ€์ž…์ด ์žˆ๋Š”์ง€ ์ด๋ฒˆ์— ์ฒ˜์Œ์— ์•Œ์•˜์Šต๋‹ˆ๋‹ค. ๐Ÿ‘ ์ €๋„ ๊ณต๋ถ€ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ใ…Žใ…Ž
@@ -0,0 +1,106 @@ +package store.config; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; +import store.error.ErrorMessage; +import store.error.exception.InvalidFailInitialDataLoadException; +import store.product.domain.Product; +import store.product.domain.ProductInfo; +import store.product.domain.ProductRepository; +import store.promotion.domain.Promotion; +import store.promotion.domain.PromotionDateTime; +import store.promotion.domain.PromotionRepository; +import store.promotion.domain.PromotionType; +import store.util.StringParser; + +public class InitialDataLoader { + + private static final String PATH_PROMOTIONS = "promotions.md"; + private static final String PATH_PRODUCTS = "products.md"; + private static final String DELIMITER_COMMA = ","; + private final PromotionRepository promotionRepository; + private final ProductRepository productRepository; + private Long promotionSequence = 1L; + private Long productSequence = 1L; + + public InitialDataLoader(final PromotionRepository promotionRepository, final ProductRepository productRepository) { + this.promotionRepository = promotionRepository; + this.productRepository = productRepository; + } + + public void initialize() { + saveAllPromotions(); + saveAllProducts(); + } + + private void saveAllPromotions() { + final Queue<String> fileLines = readFileLines(PATH_PROMOTIONS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + savePromotion(line); + } + } + + + private void saveAllProducts() { + final Queue<String> fileLines = readFileLines(PATH_PRODUCTS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + saveProduct(line); + } + } + + private void saveProduct(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Long id = productSequence++; + final Product product = createProduct(id, tokens); + productRepository.save(id, product); + } + + private Product createProduct(final Long id, final List<String> tokens) { + final String promotionName = tokens.get(3); + final Promotion promotion = promotionRepository.findByPromotionType(PromotionType.findByName(promotionName)) + .orElse(null); + final int price = StringParser.parseToNumber(tokens.get(1)); + final int quantity = StringParser.parseToNumber(tokens.get(2)); + final ProductInfo productInfo = new ProductInfo(tokens.get(0), price, promotion); + return new Product(id, productInfo, quantity); + } + + + private void savePromotion(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Promotion promotion = createPromotion(tokens); + promotionRepository.save(promotionSequence++, promotion); + } + + private Promotion createPromotion(final List<String> tokens) { + final PromotionType type = PromotionType.findByName(tokens.get(0)); + final int buy = StringParser.parseToNumber(tokens.get(1)); + final int get = StringParser.parseToNumber(tokens.get(2)); + final PromotionDateTime promotionDateTime = new PromotionDateTime(tokens.get(3), tokens.get(4)); + return new Promotion(type, promotionDateTime, buy, get); + } + + + private Queue<String> readFileLines(final String path) { + try { + URI uri = getClass().getClassLoader().getResource(path).toURI(); + return new ArrayDeque<>(Files.readAllLines(Paths.get(uri))); + } catch (Exception e) { + throw new InvalidFailInitialDataLoadException(ErrorMessage.INVALID_FAIL_INITIAL_DATA_LOAD); + } + } +}
Java
p5 ์ฝ”๋“œ๊ฐ€ ์ค‘๋ณต๋˜๊ธฐ์— ์ด๋ ‡๊ฒŒ ํ•ด๋ณด์‹œ๋Š” ๊ฒƒ๋„ ํ•˜๋‚˜์˜ ๋ฐฉ๋ฒ•์ด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋งŒ์•ฝ ๋ฏธ๋ž˜์— ๊ฐ๊ฐ์˜ ํŒŒ์ผ ์–‘์‹์ด๋‚˜ ์ดˆ๊ธฐํ™”ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์ƒ์ดํ•˜๊ฒŒ ๋ณ€๊ฒฝ๋  ๊ฒฝ์šฐ๋„ ๊ณ ๋ คํ–ˆ๋‹ค๋ฉด ์ˆ˜๋‹ฌ๋‹˜ ๋ฐฉ์‹์ด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ```suggestion public void initialize() { saveAllData(PATH_PROMOTIONS, this::savePromotion); saveAllData(PATH_PRODUCTS, this::saveProduct); } private void saveAllData(String path, Consumer<String> saveFunction) { final Queue<String> fileLines = readFileLines(path); if (fileLines.isEmpty()) { return; } fileLines.poll(); while (!fileLines.isEmpty()) { final String line = fileLines.poll(); saveFunction.accept(line); } } ```
@@ -0,0 +1,106 @@ +package store.config; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; +import store.error.ErrorMessage; +import store.error.exception.InvalidFailInitialDataLoadException; +import store.product.domain.Product; +import store.product.domain.ProductInfo; +import store.product.domain.ProductRepository; +import store.promotion.domain.Promotion; +import store.promotion.domain.PromotionDateTime; +import store.promotion.domain.PromotionRepository; +import store.promotion.domain.PromotionType; +import store.util.StringParser; + +public class InitialDataLoader { + + private static final String PATH_PROMOTIONS = "promotions.md"; + private static final String PATH_PRODUCTS = "products.md"; + private static final String DELIMITER_COMMA = ","; + private final PromotionRepository promotionRepository; + private final ProductRepository productRepository; + private Long promotionSequence = 1L; + private Long productSequence = 1L; + + public InitialDataLoader(final PromotionRepository promotionRepository, final ProductRepository productRepository) { + this.promotionRepository = promotionRepository; + this.productRepository = productRepository; + } + + public void initialize() { + saveAllPromotions(); + saveAllProducts(); + } + + private void saveAllPromotions() { + final Queue<String> fileLines = readFileLines(PATH_PROMOTIONS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + savePromotion(line); + } + } + + + private void saveAllProducts() { + final Queue<String> fileLines = readFileLines(PATH_PRODUCTS); + if (fileLines.isEmpty()) { + return; + } + fileLines.poll(); + while (!fileLines.isEmpty()) { + final String line = fileLines.poll(); + saveProduct(line); + } + } + + private void saveProduct(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Long id = productSequence++; + final Product product = createProduct(id, tokens); + productRepository.save(id, product); + } + + private Product createProduct(final Long id, final List<String> tokens) { + final String promotionName = tokens.get(3); + final Promotion promotion = promotionRepository.findByPromotionType(PromotionType.findByName(promotionName)) + .orElse(null); + final int price = StringParser.parseToNumber(tokens.get(1)); + final int quantity = StringParser.parseToNumber(tokens.get(2)); + final ProductInfo productInfo = new ProductInfo(tokens.get(0), price, promotion); + return new Product(id, productInfo, quantity); + } + + + private void savePromotion(final String line) { + final List<String> tokens = StringParser.parseToTokens(line, DELIMITER_COMMA); + final Promotion promotion = createPromotion(tokens); + promotionRepository.save(promotionSequence++, promotion); + } + + private Promotion createPromotion(final List<String> tokens) { + final PromotionType type = PromotionType.findByName(tokens.get(0)); + final int buy = StringParser.parseToNumber(tokens.get(1)); + final int get = StringParser.parseToNumber(tokens.get(2)); + final PromotionDateTime promotionDateTime = new PromotionDateTime(tokens.get(3), tokens.get(4)); + return new Promotion(type, promotionDateTime, buy, get); + } + + + private Queue<String> readFileLines(final String path) { + try { + URI uri = getClass().getClassLoader().getResource(path).toURI(); + return new ArrayDeque<>(Files.readAllLines(Paths.get(uri))); + } catch (Exception e) { + throw new InvalidFailInitialDataLoadException(ErrorMessage.INVALID_FAIL_INITIAL_DATA_LOAD); + } + } +}
Java
p4 ```suggestion private final AtomicLong promotionSequence = new AtomicLong(1); private final AtomicLong productSequence = new AtomicLong(1); ``` `AtomicLong`์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ์—๋„ ๋Œ€์‘์ด ๋˜๊ณ  `final Long id = productSequence++` ์ฒ˜๋Ÿผ ํ›„์œ„ ์ฆ๊ฐ ์—ฐ์‚ฐ์ž ๋Œ€์‹  `final Long id = productSequence.getAndIncrement()` ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด์„œ ๊ด€๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•ด์ง‘๋‹ˆ๋‹ค.
@@ -0,0 +1,67 @@ +package store.product.controller; + +import java.util.ArrayList; +import java.util.List; +import store.error.ErrorMessage; +import store.product.domain.PurchaseProduct; +import store.product.dto.PurchaseProductRequest; +import store.product.service.ProductService; +import store.product.view.ProductOutputView; +import store.state.PurchaseState; +import store.util.LoopTemplate; +import store.util.StringParser; +import store.util.StringValidator; +import store.view.InputView; + +public class ProductController { + + private final InputView inputView; + private final ProductOutputView outputView; + private final ProductService productService; + + public ProductController(final InputView inputView, final ProductOutputView outputView, + final ProductService productService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + } + + public void run() { + responseProductStatuses(); + final List<PurchaseProduct> purchaseProducts = requestPurchaseProduct(); + final PurchaseState purchaseState = PurchaseState.getInstance(); + purchaseState.updatePurchaseProducts(purchaseProducts); + } + + private void responseProductStatuses() { + outputView.printIntro(); + outputView.printProductStatus(productService.getProductStatuses()); + } + + private List<PurchaseProduct> requestPurchaseProduct() { + return LoopTemplate.tryCatchLoop(() -> { + outputView.printAskPurchaseProduct(); + final List<String> products = inputView.readProducts(); + final List<PurchaseProductRequest> purchaseProductRequests = generatePurchaseProductRequests(products); + return productService.generatePurchaseProducts(purchaseProductRequests); + }); + } + + private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> values) { + final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); + for (String value : values) { + StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); + final String product = StringParser.removePattern(value.trim(), "[\\[\\]]"); + purchaseProductRequests.add(createPurchaseProductRequest(product)); + } + return purchaseProductRequests; + } + + private PurchaseProductRequest createPurchaseProductRequest(final String product) { + final String[] splitProduct = product.split("-"); + final String name = splitProduct[0]; + final int quantity = StringParser.parseToNumber(splitProduct[1]); + return new PurchaseProductRequest(name, quantity); + } + +}
Java
p3 ํด๋ฆฐ ์ฝ”๋“œ(Clean Code, ๋กœ๋ฒ„ํŠธ C. ๋งˆํ‹ด)์—์„œ๋Š” ๋ณ€์ˆ˜๋ช…์€ ์ฝ”๋“œ์˜ ๋ชฉ์ ๊ณผ ์˜๋„๋ฅผ ๋ช…ํ™•ํžˆ ๋ณด์—ฌ์ค˜์•ผ ํ•œ๋‹ค๊ณ  ๋งํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, values ๋Œ€์‹  ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋ฌด์—‡์„ ๋‚˜ํƒ€๋‚ด๋Š”์ง€๋ฅผ ๋” ์ž˜ ํ‘œํ˜„ํ•˜๋Š” ์ด๋ฆ„์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ values๋ณด๋‹ค๋Š” rawProductInputs๋‚˜ products์™€ ๊ฐ™์ด, ๋ฆฌ์ŠคํŠธ์— ๋‹ด๊ธด ๋ฐ์ดํ„ฐ๊ฐ€ ์–ด๋–ค ๋งฅ๋ฝ์—์„œ ์‚ฌ์šฉ๋˜๋Š”์ง€ ๋ณด์—ฌ์ฃผ๋Š” ์ด๋ฆ„์ด ๋” ์ข‹์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ์ด๋ฉ๋‹ˆ๋‹ค. ์‹ค์ œ๋กœ ์ €๋„ ์ฝ”๋“œ๋ฆฌ๋ทฐํ•˜๋ฉด์„œ values๊ฐ€ ๋ญ”์ง€ ๋ชฐ๋ผ์„œ generatePurchaseProductRequests๊ฐ€ ์‚ฌ์šฉ๋œ ๊ณณ์œผ๋กœ ๊ฐ€์„œ ์ธ์ˆ˜๊ฐ€ ๋ฌด์—‡์ธ์ง€ ํ™•์ธํ–ˆ์Šต๋‹ˆ๋‹ค. ใ…œ ```suggestion private List<PurchaseProductRequest> generatePurchaseProductRequests(final List<String> products) { final List<PurchaseProductRequest> purchaseProductRequests = new ArrayList<>(); for (String product : products) { StringValidator.validateFormat(value, ErrorMessage.INVALID_FORMAT_PRODUCT_AND_QUANTITY); final String product = StringParser.removePattern(product.trim(), "[\\[\\]]"); purchaseProductRequests.add(createPurchaseProductRequest(product)); } return purchaseProductRequests; } ```
@@ -0,0 +1,34 @@ +package store; + +import camp.nextstep.edu.missionutils.Console; +import store.payment.controller.PaymentController; +import store.product.controller.ProductController; +import store.promotion.controller.PromotionController; +import store.state.PurchaseState; + +public class Convenience { + + private final ProductController productController; + private final PromotionController promotionController; + private final PaymentController paymentController; + + public Convenience(final ProductController productController, final PromotionController promotionController, + final PaymentController paymentController) { + this.productController = productController; + this.promotionController = promotionController; + this.paymentController = paymentController; + } + + public void purchase() { + do { + productController.run(); + promotionController.run(); + paymentController.run(); + } while (isRetryPurchase()); + Console.close(); + } + + private boolean isRetryPurchase() { + return PurchaseState.getInstance().isRetryPurchase(); + } +}
Java
`PurchaseState`์—์„œ `getInstatnce`๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋‚ด๋ถ€์—์„œ ์žฌ๊ตฌ๋งค๋ฅผ ํ•  ๊ฒƒ์ธ๊ฐ€์— ๋Œ€ํ•œ ๋ฉ”์„œ๋“œ๋ฅผ ์„ ์–ธํ•ด ์‚ฌ์šฉํ•˜๋ฉด, ๋””๋ฏธํ„ฐ์˜ ๋ฒ•์น™์„ ์ง€ํ‚ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์—ฌ๊ธฐ์— ๋Œ€ํ•œ ์ˆ˜๋‹ฌ๋‹˜์˜ ์˜๊ฒฌ์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,107 @@ +package store.config; + +import store.Convenience; +import store.payment.controller.PaymentController; +import store.payment.service.PaymentService; +import store.payment.view.PaymentOutputView; +import store.payment.view.console.ConsolePaymentOutputView; +import store.product.controller.ProductController; +import store.product.domain.ProductRepository; +import store.product.service.ProductService; +import store.product.service.PurchaseProductGenerator; +import store.product.view.ProductOutputView; +import store.product.view.console.ConsoleProductOutputView; +import store.promotion.controller.PromotionController; +import store.promotion.domain.PromotionRepository; +import store.promotion.service.PromotionService; +import store.promotion.view.PromotionOutputView; +import store.promotion.view.console.ConsolePromotionOutputView; +import store.view.InputView; +import store.view.console.ConsoleInputView; + +public class AppConfig { + + private final ProductRepository productRepository; + private final PromotionRepository promotionRepository; + + public AppConfig(final ProductRepository productRepository, final PromotionRepository promotionRepository) { + this.productRepository = productRepository; + this.promotionRepository = promotionRepository; + } + + public Convenience convenience() { + return new Convenience( + productController(), + promotionController(), + paymentController() + ); + } + + public InitialDataLoader initialDataLoader() { + return new InitialDataLoader( + promotionRepository, + productRepository + ); + } + + private PurchaseProductGenerator purchaseProductGenerator() { + return new PurchaseProductGenerator(productRepository); + } + + private ProductService productService() { + return new ProductService( + productRepository, + purchaseProductGenerator() + ); + } + + private PromotionService promotionService() { + return new PromotionService(productRepository); + } + + private PaymentService paymentService() { + return new PaymentService(productRepository); + } + + private InputView inputView() { + return new ConsoleInputView(); + } + + private ProductOutputView productOutputView() { + return new ConsoleProductOutputView(); + } + + private PromotionOutputView promotionOutputView() { + return new ConsolePromotionOutputView(); + } + + private PaymentOutputView paymentOutputView() { + return new ConsolePaymentOutputView(); + } + + private ProductController productController() { + return new ProductController( + inputView(), + productOutputView(), + productService() + ); + } + + private PromotionController promotionController() { + return new PromotionController( + inputView(), + promotionOutputView(), + promotionService() + ); + } + + private PaymentController paymentController() { + return new PaymentController( + inputView(), + paymentOutputView(), + paymentService() + ); + } + + +}
Java
๊ณต๋ฐฑ๋„ ์ปจ๋ฒค์…˜์ด๋‹ค! ๐Ÿ‘€
@@ -0,0 +1,108 @@ +package repository; + +import domain.Product; +import domain.PromotionType; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import java.util.Optional; + +public class ProductRepository { + public static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String FILE_LOADING_ERROR_MESSAGE = "[ERROR] ํŒŒ์ผ ๋กœ๋”ฉ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ"; + public static final String DELIMITER = ","; + public static final int NAME_INDEX = 0; + public static final int PRICE_INDEX = 1; + public static final int QUANTITY_INDEX = 2; + public static final int PROMOTION_INDEX = 3; + + private final List<Product> products = new ArrayList<>(); + private final PromotionRepository promotionRepository; + + public ProductRepository(PromotionRepository promotionRepository) { + this.promotionRepository = promotionRepository; + loadProducts(); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + skipHeader(reader); + processProductLines(reader); + } catch (IOException e) { + System.out.println(FILE_LOADING_ERROR_MESSAGE); + } + } + + private void processProductLines(BufferedReader reader) throws IOException { + String line; + while ((line = reader.readLine()) != null) { + if (!line.trim().isEmpty()) { + processProductLine(line); + } + } + } + + private void processProductLine(String line) { + String[] parts = line.split(DELIMITER); + String name = parts[NAME_INDEX].trim(); + int price = Integer.parseInt(parts[PRICE_INDEX].trim()); + int quantity = Integer.parseInt(parts[QUANTITY_INDEX].trim()); + String promotion = parts[PROMOTION_INDEX].trim(); + + PromotionType promotionType = getPromotionType(promotion); + boolean isPromo = (promotionType != PromotionType.NONE); + + addOrUpdateProduct(name, price, quantity, promotion, promotionType, isPromo); + } + + private void addOrUpdateProduct(String name, int price, int quantity, String promotion, + PromotionType promotionType, boolean isPromo) { + findExistingProduct(name).ifPresentOrElse( + product -> updateProductQuantity(product, quantity, isPromo), + () -> addNewProduct(name, price, quantity, promotion, promotionType, isPromo) + ); + } + + private void updateProductQuantity(Product product, int quantity, boolean isPromo) { + if (isPromo) { + product.addPromotionQuantity(quantity); + return; + } + product.addGeneralQuantity(quantity); + } + + private void addNewProduct(String name, int price, int quantity, String promotion, PromotionType promotionType, + boolean isPromo) { + Product newProduct = new Product(name, price, quantity, promotion, promotionType, isPromo); + products.add(newProduct); + } + + private Optional<Product> findExistingProduct(String name) { + return products.stream() + .filter(p -> Objects.equals(p.getName(), name)) + .findFirst(); + } + + private PromotionType getPromotionType(String promotion) { + return promotionRepository.getPromotionTypeByName(promotion) + .orElse(PromotionType.NONE); + } + + private void skipHeader(BufferedReader reader) throws IOException { + reader.readLine(); + } + + public List<Product> getProducts() { + return products; + } + + public Optional<Product> findProductByName(String productName) { + return products.stream() + .filter(product -> Objects.equals(product.getName(), productName)) + .findFirst(); + } +}
Java
๋ณดํ†ต ์ด๋Ÿฐ ๋ ˆํŒŒ์ง€ํ† ๋ฆฌ ํ˜•ํƒœ๋Š” Map ์ž๋ฃŒํ˜•์„ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š”๋ฐ์š” List ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•˜์‹  ์˜๋„๊ฐ€ ๊ถ๊ธˆํ•ด์š” ใ…Žใ…Ž!
@@ -0,0 +1,84 @@ +package service; + +import java.util.ArrayList; +import repository.ProductRepository; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class InputHandler { + private final static String INVALID_INPUT_FORMAT = "[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final Pattern INPUT_PATTERN = Pattern.compile("\\[(.+)-([0-9]+)]"); + public static final String COMMA_PATTERN = ","; + public static final String PAIR_PATTERN = "\\[.+?]"; + public static final String DELIMITER = ","; + + private final ProductRepository productRepository; + + public InputHandler(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public List<RequestedProduct> processInput(String items) { + validateInputFormat(items); + return parseRequestedProductList(items); + } + + private void validateInputFormat(String items) { + if (items == null || items.isBlank()) { + throw new IllegalArgumentException(INVALID_INPUT_FORMAT); + } + int pairCount = countPattern(items, PAIR_PATTERN); + int commaCount = countPattern(items, COMMA_PATTERN); + + if (pairCount > 1 && commaCount != pairCount - 1) { + throw new IllegalArgumentException(INVALID_INPUT_FORMAT); + } + } + + private int countPattern(String input, String pattern) { + Matcher matcher = Pattern.compile(pattern).matcher(input); + int count = 0; + while (matcher.find()) { + count++; + } + return count; + } + + private List<RequestedProduct> parseRequestedProductList(String items) { + Map<String, Integer> productMap = parseProductMap(items); + return createRequestedProduct(productMap); + } + + private List<RequestedProduct> createRequestedProduct(Map<String, Integer> productMap) { + List<RequestedProduct> requestedProductList = new ArrayList<>(); + for (Map.Entry<String, Integer> entry : productMap.entrySet()) { + RequestedProduct requestedProduct = new RequestedProduct(entry.getKey(), entry.getValue(), + productRepository); + requestedProductList.add(requestedProduct); + } + return requestedProductList; + } + + private Map<String, Integer> parseProductMap(String items) { + Map<String, Integer> productMap = new LinkedHashMap<>(); + for (String item : items.split(DELIMITER)) { + Matcher matcher = validateAndMatchInput(item); + String productName = matcher.group(1); + int productAmount = Integer.parseInt(matcher.group(2)); + productMap.put(productName, productMap.getOrDefault(productName, 0) + productAmount); + } + return productMap; + } + + private Matcher validateAndMatchInput(String item) { + Matcher matcher = INPUT_PATTERN.matcher(item); + if (!matcher.matches()) { + throw new IllegalArgumentException(INVALID_INPUT_FORMAT); + } + return matcher; + } +}
Java
์ •๊ทœํ‘œํ˜„์‹๊ณผ ๋ณด๋ฉด ์ˆ˜๋Ÿ‰์ด 0๊ฐœ์ธ ๊ฒฝ์šฐ๋„ ํ†ต๊ณผ ๋˜๋Š”๊ฑธ๋กœ ๋ณด์ด๋Š”๋ฐ์š” ํ˜น์‹œ 0๊ฐœ๋„ ํ—ˆ์šฉํ•˜์‹  ์˜๋„๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š” ??
@@ -0,0 +1,144 @@ +package service; + +import domain.Membership; +import domain.Product; +import domain.PromotionType; +import domain.PurchaseProduct; +import domain.Receipt; +import java.util.List; +import repository.ProductRepository; +import view.InputView; + +public class OrderService { + public static final String PRODUCT_NOT_FOUND = "[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String CONFIRM_FREE_ITEM_ADDITION = "Y"; + public static final String CONFIRM_PURCHASE_WITHOUT_PROMOTION = "N"; + public static final String CONFIRM_USE_MEMBERSHIP = "Y"; + + private final ProductRepository productRepository; + private final Membership membership; + + public OrderService(ProductRepository productRepository, Membership membership) { + this.productRepository = productRepository; + this.membership = membership; + } + + public Receipt createOrder(List<RequestedProduct> requestedProducts) { + Receipt receipt = new Receipt(); + for (RequestedProduct requestedProduct : requestedProducts) { + processRequestedProduct(requestedProduct, receipt); + } + applyMembershipDiscount(receipt); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + if (InputView.confirmUseMembership().equals(CONFIRM_USE_MEMBERSHIP)) { + receipt.useMembership(membership); + } + } + + private void processRequestedProduct(RequestedProduct requestedProduct, Receipt receipt) { + Product stockProduct = findStockProduct(requestedProduct.getProductName()); + PurchaseProduct totalProduct = createPurchaseProduct(requestedProduct); + + if (stockProduct.hasPromo()) { + handlePromotion(stockProduct, totalProduct, requestedProduct.getQuantity(), receipt); + return; + } + applyGeneralItem(stockProduct, totalProduct, receipt); + } + + private void applyGeneralItem(Product stockProduct, PurchaseProduct totalProduct, Receipt receipt) { + receipt.applyGeneralItem(totalProduct); + stockProduct.reduceGeneralQuantity(totalProduct.getQuantity()); + } + + private void handlePromotion(Product stockProduct, PurchaseProduct totalProduct, int quantity, Receipt receipt) { + int promotionQuantity = stockProduct.getPromotionQuantity(); + PromotionType promotionType = stockProduct.getPromotionType(); + int buyCount = promotionType.getBuyCount(); + + if(promotionQuantity<=buyCount){ + applyGeneralItem(stockProduct,totalProduct,receipt); + return; + } + int divisor = promotionType.getDivisor(); + if (isAvailableForFreeItem(quantity, divisor, promotionQuantity)) { + quantity = addFreeItem(totalProduct, quantity); + } + if (promotionQuantity >= quantity) { + applyPromotion(stockProduct, totalProduct, quantity, receipt, divisor); + return; + } + handleInsufficientPromotionStock(stockProduct, totalProduct, promotionQuantity, quantity, receipt, divisor); + } + + private void handleInsufficientPromotionStock(Product stockProduct, PurchaseProduct totalProduct, + int promotionQuantity, int quantity, Receipt receipt, int divisor) { + int usedTotalPromoProduct = (promotionQuantity / divisor) * divisor; + stockProduct.reducePromotionQuantity(usedTotalPromoProduct); + + PurchaseProduct promoProduct = createPromoProduct(stockProduct, usedTotalPromoProduct, divisor); + int restPromoQuantity = promotionQuantity - usedTotalPromoProduct; + stockProduct.reducePromotionQuantity(restPromoQuantity); + stockProduct.addGeneralQuantity(restPromoQuantity); + + int insufficientQuantity = quantity - usedTotalPromoProduct; + adjustForInsufficientQuantity(stockProduct, totalProduct, insufficientQuantity); + + if (promoProduct != null) { + receipt.applyPromoItem(promoProduct, divisor); + } + receipt.applyGeneralItem(totalProduct); + } + + private void adjustForInsufficientQuantity(Product stockProduct, PurchaseProduct totalProduct, + int insufficientQuantity) { + if (InputView.confirmPurchaseWithoutPromotion(totalProduct.getName(), insufficientQuantity) + .equals(CONFIRM_PURCHASE_WITHOUT_PROMOTION)) { + totalProduct.subtractQuantity(insufficientQuantity); + return; + } + stockProduct.reduceGeneralQuantity(insufficientQuantity); + } + + private PurchaseProduct createPromoProduct(Product stockProduct, int usedTotalPromoProduct, int divisor) { + if (usedTotalPromoProduct == 0) { + return null; + } + return new PurchaseProduct(stockProduct.getName(), usedTotalPromoProduct / divisor, stockProduct.getPrice()); + } + + + private void applyPromotion(Product stockProduct, PurchaseProduct totalProduct, int quantity, Receipt receipt, + int divisor) { + PurchaseProduct promoProduct = new PurchaseProduct(totalProduct.getName(), quantity / divisor, + totalProduct.getPrice()); + stockProduct.reducePromotionQuantity(quantity); + receipt.applyPromoItem(promoProduct, divisor); + receipt.applyGeneralItem(totalProduct); + } + + private boolean isAvailableForFreeItem(int quantity, int divisor, int promotionQuantity) { + return quantity % divisor == divisor - 1 && promotionQuantity >= quantity + 1; + } + + private int addFreeItem(PurchaseProduct totalProduct, int quantity) { + if (InputView.confirmFreeItemAddition(totalProduct.getName()).equals(CONFIRM_FREE_ITEM_ADDITION)) { + totalProduct.addGiveawayQuantity(); + quantity += 1; + } + return quantity; + } + + private PurchaseProduct createPurchaseProduct(RequestedProduct requestedProduct) { + return new PurchaseProduct(requestedProduct.getProductName(), requestedProduct.getQuantity(), + requestedProduct.getPrice()); + } + + private Product findStockProduct(String name) { + return productRepository.findProductByName(name).orElseThrow(() -> new IllegalArgumentException( + PRODUCT_NOT_FOUND)); + } +}
Java
ํ•ด๋‹น ํด๋ž˜์Šค๋ฅผ ๋ณด๋ฉด ์ƒํ’ˆ, ํ”„๋กœ๋ชจ์…˜, ๋ฉค๋ฒ„์‹ญ์˜ ์ฑ…์ž„์„ ๋ชจ๋‘ ๊ฐ–๊ณ  ์žˆ๋Š”๋ฐ์š” ์ฑ…์ž„์ด ๋งŽ๋‹ค ๋ณด๋‹ˆ๊นŒ private ๋ฉ”์„œ๋“œ๋„ ๋งŽ์•„์ง€๊ณ , ์ฝ”๋“œ ๋ผ์ธ๋„ 120์ค„์ด ๋„˜์–ด๊ฐ€๋„ค์š” ๊ทธ๋ฆฌ๊ณ  ์„œ๋น„์Šค๋„ View์— ์˜์กดํ•˜๊ณ  ์žˆ๊ตฌ์š” ๊ทธ๋ž˜์„œ ์ƒํ’ˆ, ํ”„๋กœ๋ชจ์…˜, ๋ฉค๋ฒ„์‹ญ ์ด 3๊ฐ€์ง€ ์„œ๋น„์Šค๋กœ ์ชผ๊ฐœ๋ฉด ์–ด๋–จ๊นŒํ•ด์š”~ ๋ฒ”์„๋‹˜ ์ƒ๊ฐ์€ ์–ด๋– ์„ธ์š”??
@@ -0,0 +1,73 @@ +package view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String[] YES_OPTIONS = {"Y", "y"}; + private static final String[] NO_OPTIONS = {"N", "n"}; + + private static final String ITEM_INPUT_PROMPT = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + private static final String CONFIRM_FREE_ITEM_ADDITION_PROMPT = "ํ˜„์žฌ %s์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + private static final String CONFIRM_PURCHASE_WITHOUT_PROMOTION_PROMPT = "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + private static final String CONFIRM_USE_MEMBERSHIP_PROMPT = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + private static final String CONFIRM_ADDITIONAL_PURCHASE_PROMPT = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String ERROR_INVALID_INPUT = "[ERROR] ์˜ฌ๋ฐ”๋ฅธ ๊ฐ’์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (Y/N)"; + + public static String readItem() { + System.out.print(System.lineSeparator()); + System.out.println(ITEM_INPUT_PROMPT); + return Console.readLine(); + } + + public static String confirmFreeItemAddition(String productName) { + System.out.print(System.lineSeparator()); + System.out.printf(CONFIRM_FREE_ITEM_ADDITION_PROMPT + "%n", productName); + return validateYesOrNo(); + } + + public static String confirmPurchaseWithoutPromotion(String productName, int quantity) { + System.out.print(System.lineSeparator()); + System.out.printf(CONFIRM_PURCHASE_WITHOUT_PROMOTION_PROMPT + "%n", productName, quantity); + return validateYesOrNo(); + } + + public static String confirmUseMembership() { + System.out.print(System.lineSeparator()); + System.out.println(CONFIRM_USE_MEMBERSHIP_PROMPT); + return validateYesOrNo(); + } + + public static String confirmAdditionalPurchase() { + System.out.print(System.lineSeparator()); + System.out.println(CONFIRM_ADDITIONAL_PURCHASE_PROMPT); + return validateYesOrNo(); + } + + private static String validateYesOrNo() { + while (true) { + String input = Console.readLine().trim(); + if (isYes(input) || isNo(input)) { + return input.toUpperCase(); + } + System.out.println(ERROR_INVALID_INPUT); + } + } + + private static boolean isYes(String input) { + for (String yesOption : YES_OPTIONS) { + if (yesOption.equals(input)) { + return true; + } + } + return false; + } + + private static boolean isNo(String input) { + for (String noOption : NO_OPTIONS) { + if (noOption.equals(input)) { + return true; + } + } + return false; + } +} \ No newline at end of file
Java
์‚ฌ์šฉ์ž์˜ ์‘๋‹ต์„ ํŒ๋‹จํ•˜๋Š”๊ฒƒ๋„ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์ค‘ ํ•˜๋‚˜๋ผ๊ณ  ์ƒ๊ฐ์„ ํ•ด์š” ์™œ๋ƒํ•˜๋ฉด ์‘๋‹ต์— ๋”ฐ๋ผ์„œ ํ”„๋กœ๋ชจ์…˜, ๋ฉค๋ฒ„์‹ญ ํ˜œํƒ๋“ฑ์ด ๋‹ฌ๋ผ์ง€๋‹ˆ๊นŒ์š” ๊ทธ๋ž˜์„œ ์š”๋ถ€๋ถ„์€ ์„œ๋น„์Šค์—์„œ ๋‹ด๋‹นํ•˜๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•ด์š” ๋ฒ”์„๋‹˜ ์˜๊ฒฌ์€ ์–ด๋– ์„ธ์š” ??
@@ -0,0 +1,95 @@ +package view; + +import domain.Product; +import domain.PromotionType; +import domain.PurchaseProduct; +import java.text.NumberFormat; +import java.util.List; + +public class OutputView { + private static final NumberFormat currencyFormat = NumberFormat.getInstance(); + + public static final String GREETING_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.%nํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค.%n%n"; + public static final String RECEIPT_HEADER = "\n===========W ํŽธ์˜์ ============="; + public static final String PROMOTION_HEADER = "===========์ฆ ์ •============="; + public static final String RECEIPT_DIVIDER = "=============================="; + public static final String TOTAL_AMOUNT = "์ด๊ตฌ๋งค์•ก"; + public static final String PROMOTION_DISCOUNT = "ํ–‰์‚ฌํ• ์ธ"; + public static final String MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญํ• ์ธ"; + public static final String FINAL_AMOUNT = "๋‚ด์‹ค๋ˆ"; + + public static void printProducts(List<Product> products) { + greetingMessage(); + for (Product product : products) { + printProductByPromotion(product); + } + } + + private static void printProductByPromotion(Product product) { + String formattedPrice = formatCurrency(product.getPrice()); + if (product.getPromotionType() != PromotionType.NONE) { + printPromotionProduct(product, formattedPrice); + } + printGeneralProduct(product, formattedPrice); + } + + private static void greetingMessage() { + System.out.print(System.lineSeparator()); + System.out.printf(GREETING_MESSAGE); + } + + private static void printPromotionProduct(Product product, String formattedPrice) { + if (product.getPromotionQuantity() > 0) { + String formattedPromoQuantity = formatCurrency(product.getPromotionQuantity()); + System.out.printf("- %s %s์› %s๊ฐœ %s%n", product.getName(), formattedPrice, formattedPromoQuantity, + product.getPromotionName()); + return; + } + System.out.printf("- %s %s์› ์žฌ๊ณ  ์—†์Œ %s%n", product.getName(), formattedPrice, + product.getPromotionName()); + } + + private static void printGeneralProduct(Product product, String formattedPrice) { + if (product.getGeneralQuantity() > 0) { + String formattedGeneralQuantity = formatCurrency(product.getGeneralQuantity()); + System.out.printf("- %s %s์› %s๊ฐœ%n", product.getName(), formattedPrice, formattedGeneralQuantity); + return; + } + System.out.printf("- %s %s์› ์žฌ๊ณ  ์—†์Œ%n", product.getName(), formattedPrice); + } + + public static void printReceipt(List<PurchaseProduct> purchasedItems) { + System.out.println(RECEIPT_HEADER); + System.out.printf("%-14s %-6s %-6s%n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + + for (PurchaseProduct item : purchasedItems) { + int totalPrice = item.getPrice() * item.getQuantity(); + System.out.printf("%-14s %-6d %-6s%n", item.getName(), item.getQuantity(), formatCurrency(totalPrice)); + } + } + + public static void printPromotionReceipt(List<PurchaseProduct> promoItems) { + System.out.println(PROMOTION_HEADER); + for (PurchaseProduct item : promoItems) { + System.out.printf("%-13s %-6s%n", item.getName(), item.getQuantity()); + } + } + + public static void printReceiptSummary(int totalAmount, int totalQuantity, int promotionDiscount, + int membershipDiscount) { + System.out.println(RECEIPT_DIVIDER); + System.out.printf("%-14s %-6d %-6s%n", TOTAL_AMOUNT, totalQuantity, formatCurrency(totalAmount)); + System.out.printf("%-20s %-6s%n", PROMOTION_DISCOUNT, formatCurrencyWithMinus(promotionDiscount)); + System.out.printf("%-20s %-6s%n", MEMBERSHIP_DISCOUNT, formatCurrencyWithMinus(membershipDiscount)); + System.out.printf("%-20s %-6s%n", FINAL_AMOUNT, + formatCurrency(totalAmount - promotionDiscount - membershipDiscount)); + } + + private static String formatCurrency(int value) { + return currencyFormat.format(value); + } + + private static String formatCurrencyWithMinus(int amount) { + return "-" + formatCurrency(amount); + } +}
Java
์‚ฌ์†Œํ•œ๊ฑฐ์ง€๋งŒ, ์ถœ๋ ฅ๋ฌธ์€ ์ปค๋„ ์˜์—ญ์—์„œ ์‹คํ–‰๋˜๋Š” ์ž‘์—…์ด๊ธฐ ๋•Œ๋ฌธ์— ํ˜ธ์ถœ๋  ๋•Œ๋งˆ๋‹ค ์ปจํ…์ŠคํŠธ ์Šค์œ„์นญ์ด ๋ฐœ์ƒํ•ด์š” ๊ทธ๋ž˜์„œ ํ•˜๋‚˜์˜ ๋ฉ”์„ธ์ง€๋กœ ๋งŒ๋“ค์–ด์„œ ํ•œ๋ฒˆ์— ์ถœ๋ ฅํ•˜๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒํ•ด์š”~
@@ -0,0 +1,32 @@ +package domain; + +public enum PromotionType { + NONE(1, 0), + BUY_ONE_GET_ONE(1, 1), + BUY_TWO_GET_ONE(2, 1); + + private final int buyCount; + private final int giveawayCount; + + PromotionType(int buyCount, int giveawayCount) { + this.buyCount = buyCount; + this.giveawayCount = giveawayCount; + } + + public int getDivisor() { + return this.buyCount + this.giveawayCount; + } + + public int getBuyCount() { + return this.buyCount; + } + + public static PromotionType fromBuyAndGet(int buy, int get) { + for (PromotionType type : PromotionType.values()) { + if (type.buyCount == buy && type.giveawayCount == get) { + return type; + } + } + return NONE; + } +} \ No newline at end of file
Java
ํ”„๋กœ๋ชจ์…˜ ํƒ€์ž…์„ ๋ฏธ๋ฆฌ ์ •ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„์€ ๊ฐ™๊ณ  ๋‚ด์šฉ์ด ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ์œผ๋‹ˆ๊นŒ์š”.
@@ -0,0 +1,108 @@ +package repository; + +import domain.Product; +import domain.PromotionType; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import java.util.Optional; + +public class ProductRepository { + public static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String FILE_LOADING_ERROR_MESSAGE = "[ERROR] ํŒŒ์ผ ๋กœ๋”ฉ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ"; + public static final String DELIMITER = ","; + public static final int NAME_INDEX = 0; + public static final int PRICE_INDEX = 1; + public static final int QUANTITY_INDEX = 2; + public static final int PROMOTION_INDEX = 3; + + private final List<Product> products = new ArrayList<>(); + private final PromotionRepository promotionRepository; + + public ProductRepository(PromotionRepository promotionRepository) { + this.promotionRepository = promotionRepository; + loadProducts(); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + skipHeader(reader); + processProductLines(reader); + } catch (IOException e) { + System.out.println(FILE_LOADING_ERROR_MESSAGE); + } + } + + private void processProductLines(BufferedReader reader) throws IOException { + String line; + while ((line = reader.readLine()) != null) { + if (!line.trim().isEmpty()) { + processProductLine(line); + } + } + } + + private void processProductLine(String line) { + String[] parts = line.split(DELIMITER); + String name = parts[NAME_INDEX].trim(); + int price = Integer.parseInt(parts[PRICE_INDEX].trim()); + int quantity = Integer.parseInt(parts[QUANTITY_INDEX].trim()); + String promotion = parts[PROMOTION_INDEX].trim(); + + PromotionType promotionType = getPromotionType(promotion); + boolean isPromo = (promotionType != PromotionType.NONE); + + addOrUpdateProduct(name, price, quantity, promotion, promotionType, isPromo); + } + + private void addOrUpdateProduct(String name, int price, int quantity, String promotion, + PromotionType promotionType, boolean isPromo) { + findExistingProduct(name).ifPresentOrElse( + product -> updateProductQuantity(product, quantity, isPromo), + () -> addNewProduct(name, price, quantity, promotion, promotionType, isPromo) + ); + } + + private void updateProductQuantity(Product product, int quantity, boolean isPromo) { + if (isPromo) { + product.addPromotionQuantity(quantity); + return; + } + product.addGeneralQuantity(quantity); + } + + private void addNewProduct(String name, int price, int quantity, String promotion, PromotionType promotionType, + boolean isPromo) { + Product newProduct = new Product(name, price, quantity, promotion, promotionType, isPromo); + products.add(newProduct); + } + + private Optional<Product> findExistingProduct(String name) { + return products.stream() + .filter(p -> Objects.equals(p.getName(), name)) + .findFirst(); + } + + private PromotionType getPromotionType(String promotion) { + return promotionRepository.getPromotionTypeByName(promotion) + .orElse(PromotionType.NONE); + } + + private void skipHeader(BufferedReader reader) throws IOException { + reader.readLine(); + } + + public List<Product> getProducts() { + return products; + } + + public Optional<Product> findProductByName(String productName) { + return products.stream() + .filter(product -> Objects.equals(product.getName(), productName)) + .findFirst(); + } +}
Java
์œ„ skipHeader๋Š” PromotionRepository์—์„œ๋„ ์‚ฌ์šฉํ•˜์‹œ๋Š” ๊ฑธ๋กœ ์ดํ•ดํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ๋”ฐ๋กœ util๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ๊ณ ๋ คํ•ด๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค.
@@ -0,0 +1,61 @@ +package domain; + +import java.util.ArrayList; +import java.util.List; +import view.OutputView; + +public class Receipt { + private static final int INITIAL_AMOUNT = 0; + private static final int INITIAL_QUANTITY = 0; + + private final List<PurchaseProduct> purchasedItems; + private final List<PurchaseProduct> promoItems; + private int totalAmount; + private int promotionDiscount; + private int membershipDiscount; + private int totalGeneralAmount; + private int totalQuantity; + + public Receipt() { + this.purchasedItems = new ArrayList<>(); + this.promoItems = new ArrayList<>(); + this.totalAmount = INITIAL_AMOUNT; + this.promotionDiscount = INITIAL_AMOUNT; + this.membershipDiscount = INITIAL_AMOUNT; + this.totalGeneralAmount = INITIAL_AMOUNT; + this.totalQuantity = INITIAL_QUANTITY; + + } + + public void applyPromoItem(PurchaseProduct promoProduct, int divisor) { + promoItems.add(promoProduct); + int promoAmount = calculateAmount(promoProduct); + promotionDiscount += promoAmount; + totalGeneralAmount -= promoAmount * divisor; + } + + public void applyGeneralItem(PurchaseProduct purchaseProduct) { + purchasedItems.add(purchaseProduct); + int purchaseAmount = calculateAmount(purchaseProduct); + totalAmount += purchaseAmount; + totalGeneralAmount += purchaseAmount; + totalQuantity += purchaseProduct.getQuantity(); + } + + public int calculateAmount(PurchaseProduct product) { + return product.getPrice() * product.getQuantity(); + } + + + public void useMembership(Membership membership) { + membershipDiscount = membership.useMembership(totalGeneralAmount); + } + + public void print() { + OutputView.printReceipt(purchasedItems); + if (!promoItems.isEmpty()) { + OutputView.printPromotionReceipt(promoItems); + } + OutputView.printReceiptSummary(totalAmount, totalQuantity, promotionDiscount, membershipDiscount); + } +}
Java
๋„๋ฉ”์ธ ๊ฐ์ฒด์—์„œ ๋ฐ”๋กœ View๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์€ Layer๋ฅผ ๋‚˜๋ˆˆ ์˜๋ฏธ๊ฐ€ ์‚ฌ๋ผ์ง„๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. Controller์—์„œ ์ด ๊ธฐ๋Šฅ์„ ์œ„์ž„์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์œผ๋‹ˆ ํ•œ๋ฒˆ ๊ณ ๋ คํ•ด๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค.
@@ -0,0 +1,75 @@ +package store.view; + +import store.model.GiftProduct; +import store.model.Product; +import store.model.receipt.AmountInfo; +import store.model.receipt.GiftProducts; +import store.model.receipt.PurchaseProducts; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class OutputView { + public void printStoreMenu() throws IOException { + System.out.println(""" + ์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. + ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + """); + + BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/products.md")); + String product; + + reader.readLine(); + + while ((product = reader.readLine()) != null) { + String[] str = product.split(","); + System.out.printf("- %s %s์› %s %s", str[0], String.format("%,d", Integer.parseInt(str[1])), changeNoStock(str[2]), changeNull(str[3])); + System.out.println(); + } + reader.close(); + } + + public void printPurchaseProduct(PurchaseProducts purchaseProducts) { + System.out.println("==============W ํŽธ์˜์ ================"); + System.out.println("์ƒํ’ˆ๋ช…\t\t\t\t์ˆ˜๋Ÿ‰\t\t๊ธˆ์•ก"); + for (Product product : purchaseProducts.getPurchaseProducts()) { + System.out.printf("%-4s\t\t\t\t%s\t\t%s\n", product.getName(), product.getQuantity(), String.format("%,d", product.getQuantity() * product.getPrice())); + } + } + + public void printGiftProducts(GiftProducts giftProducts) { + System.out.println("=============์ฆ\t\t์ •==============="); + for (GiftProduct giftProduct : giftProducts.getGiftProducts()) { + System.out.printf("%-4s\t\t\t\t%d", giftProduct.getName(), giftProduct.getQuantity()); + System.out.println(); + } + } + + public void printAmountInfo(AmountInfo amountInfo) { + System.out.println("===================================="); + System.out.printf("์ด๊ตฌ๋งค์•ก\t\t\t\t%s\t\t%s", amountInfo.getTotalPurchaseCount(), String.format("%,d", amountInfo.getTotalPurchaseAmount())); + System.out.println(); + System.out.printf("ํ–‰์‚ฌํ• ์ธ\t\t\t\t\t\t%s", String.format("-%,d", amountInfo.getPromotionDiscount())); + System.out.println(); + System.out.printf("๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t\t\t\t%s", String.format("-%,d", amountInfo.getMembershipDiscount())); + System.out.println(); + System.out.printf("๋‚ด์‹ค๋ˆ\t\t\t\t\t\t%s", String.format("%,d", amountInfo.getPayment())); + System.out.println(); + } + + private String changeNull(String input) { + if (input.equals("null")) { + return ""; + } + return input; + } + + private String changeNoStock(String input) { + if (input.equals("0")) { + return "์žฌ๊ณ  ์—†์Œ"; + } + input = String.format("%,d", Integer.parseInt(input)); + return input + "๊ฐœ"; + } +}
Java
``StockManageService``์—์„œ๋„ mdํŒŒ์ผ์— ์ ‘๊ทผํ•˜๊ณ  ์žˆ๊ณ , ``OutputView``์—์„œ๋„ mdํŒŒ์ผ์— ์ ‘๊ทผํ•˜๊ณ  ์žˆ๋„ค์š”. ๊ฐœ์ธ์ ์œผ๋กœ ์ €๋Š” ์ด๋ฒˆ ๋ฏธ์…˜์„ ์ง„ํ–‰ํ•˜๋ฉด์„œ mdํŒŒ์ผ = ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ  ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ๋งŒ์•ฝ ์ €์™€ ๊ฐ™์€ ์ ‘๊ทผ์ด๋ผ๋ฉด ๋ทฐ์—์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์ด ์˜ณ์€ ๋ฐฉ๋ฒ•์ผ๊นŒ์š”?๐Ÿค” ํ•˜์˜๋‹˜๊ป˜์„œ๋Š” mdํŒŒ์ผ์„ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๊ณ  ์ ‘๊ทผํ•˜์…จ์„๊นŒ์š”?
@@ -0,0 +1,39 @@ +package store.model.receipt; + +import store.model.Product; + +import java.io.IOException; + +import java.util.ArrayList; +import java.util.List; + +public class PurchaseProducts { + private final List<Product> purchaseProducts; + + public PurchaseProducts(String input) throws IOException { + purchaseProducts = new ArrayList<>(); + validate(input); + } + + private void validate(String input) throws IOException { + String[] inputProducts = input.split(",", -1); + for (String product : inputProducts) { + Product pro = new Product(product); + validate(pro); + purchaseProducts.add(pro); + } + } + + private void validate(Product product){ + String target = product.getName(); + for (Product pro : purchaseProducts) { + if (pro.getName().equals(target)) { + throw new IllegalArgumentException("[ERROR] ์ค‘๋ณต๋˜๋Š” ์ƒํ’ˆ ์ด๋ฆ„์ด ์žˆ์Šต๋‹ˆ๋‹ค."); + } + } + } + + public List<Product> getPurchaseProducts() { + return purchaseProducts; + } +}
Java
```suggestion Product product = new Product(inputProduct); ``` ์ด๋ ‡๊ฒŒ ๋„ค์ด๋ฐํ•œ๋‹ค๋ฉด ํ—ท๊ฐˆ๋ฆฌ์ง€๋„ ์•Š๊ณ  ``pro``๋ผ๊ณ  ์ค„์ผ์ง€ ์•Š์•„๋„ ๋˜์ง€ ์•Š์•„์„œ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,39 @@ +package store.model.receipt; + +import store.model.Product; + +import java.io.IOException; + +import java.util.ArrayList; +import java.util.List; + +public class PurchaseProducts { + private final List<Product> purchaseProducts; + + public PurchaseProducts(String input) throws IOException { + purchaseProducts = new ArrayList<>(); + validate(input); + } + + private void validate(String input) throws IOException { + String[] inputProducts = input.split(",", -1); + for (String product : inputProducts) { + Product pro = new Product(product); + validate(pro); + purchaseProducts.add(pro); + } + } + + private void validate(Product product){ + String target = product.getName(); + for (Product pro : purchaseProducts) { + if (pro.getName().equals(target)) { + throw new IllegalArgumentException("[ERROR] ์ค‘๋ณต๋˜๋Š” ์ƒํ’ˆ ์ด๋ฆ„์ด ์žˆ์Šต๋‹ˆ๋‹ค."); + } + } + } + + public List<Product> getPurchaseProducts() { + return purchaseProducts; + } +}
Java
๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ``input``์„ ๋ฐ›๋Š” ``validate``์™€ ``product``๋ฅผ ๋ฐ›๋Š” ``validate``๋ฅผ ๋™์ผํ•œ ๋ฉ”์„œ๋“œ๋ช…์œผ๋กœ ๋ช…๋ช…ํ•˜์‹  ๊ฒƒ์— ์˜๋„๊ฐ€ ์žˆ์œผ์…จ์„๊นŒ์š”? ๋ฆฌ๋ทฐ์ด ์ž…์žฅ์—์„œ๋Š” ``validateInput``, ``validateDuplicate``์™€ ๊ฐ™์€ ๋ฉ”์„œ๋“œ๋ช…์ด์—ˆ๋‹ค๋ฉด ์˜ค์ž‰? ๊ฐ™์€ ์™œ ๊ฐ™์€ ๋ฉ”์„œ๋“œ๋ช…์ด์ง€? ๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์ง€ ์•Š์•˜์„ ๊ฒƒ ๊ฐ™์•„์„œ์š”!
@@ -0,0 +1,240 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Product { + private final String name; + private int quantity; + private int price; + private int promotionStockCount; + private int normalStockCount; + private String promotion; + private int promotionCount; + private int promotionBuyCount; + private int promotionGetCount; + private int justPromotionStockCount; + + public Product(String product) throws IOException { + initCount(); + String[] productInfo = validate(product); + name = productInfo[0]; + quantity = Integer.parseInt(productInfo[1]); + } + + private void initCount() { + promotionStockCount = 0; + normalStockCount = 0; + promotion = "null"; + promotionCount = 0; + promotionBuyCount = 0; + promotionGetCount = 0; + } + + private String[] validate(String product) throws IOException { + if (product.isBlank() | product.isEmpty()) { + throw new IllegalArgumentException("[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + product = product.replaceAll("\\s", ""); + + if (!(product.charAt(0) == '[' && product.charAt(product.length() - 1) == ']' && product.contains("-"))) { + throw new IllegalArgumentException("[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + product = product.substring(1, product.length() - 1); + String[] oneProduct = product.split("-", -1); + + for (String one : oneProduct) { + if (one.isBlank() | one.isEmpty()) { + throw new IllegalArgumentException("[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + try { + Integer.parseInt(oneProduct[1]); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + if (Integer.parseInt(oneProduct[1]) <= 0) { + throw new IllegalArgumentException("[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + if (!isExistProduct(oneProduct[0])) { + throw new IllegalArgumentException("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + if (isStockLack(oneProduct)) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + return oneProduct; + } + + private boolean isExistProduct(String productName) throws IOException { + BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/products.md")); + String food; + reader.readLine(); + + while ((food = reader.readLine()) != null) { + String foodName = food.split(",")[0]; + String foodPrice = food.split(",")[1]; + + if (foodName.equals(productName)) { + price = Integer.parseInt(foodPrice); + reader.close(); + return true; + } + } + reader.close(); + return false; + } + + private boolean isStockLack(String[] productInfo) throws IOException { + BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/products.md")); + String food; + reader.readLine(); + + while ((food = reader.readLine()) != null) { + String foodName = food.split(",")[0]; + String foodQuantity = food.split(",")[2]; + String foodPromotion = food.split(",")[3]; + + if (foodName.equals(productInfo[0]) & !foodPromotion.equals("null")) { + promotionCount = getPromotionCount(foodPromotion); // 0์ด๋ผ๋Š” ๊ฒƒ์€ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ด ์•„๋‹˜ + promotion = foodPromotion; //ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ + if (promotionCount != 0) { + promotionStockCount += Integer.parseInt(foodQuantity); + } + justPromotionStockCount = Integer.parseInt(foodQuantity); + } + if (foodName.equals(productInfo[0]) & foodPromotion.equals("null")) { + normalStockCount += Integer.parseInt(foodQuantity); + } + } + if (justPromotionStockCount + normalStockCount < Integer.parseInt(productInfo[1])) { + reader.close(); + return true; + } + reader.close(); + return false; + } + + public boolean isAvailableOnlyPromotion() { + return promotionStockCount > quantity; + } + + public boolean isSameWithQuantity() { + return promotionStockCount == quantity; + } + + public int countPromotionDisable() { + int count = decreasePromotionStock() + decreaseNormalStock(); + if (count >= promotionBuyCount) { + return count; + } + return 0; + } + + public int buyOnlyPromotion() { + quantity = promotionStockCount - decreasePromotionStock(); + return quantity; + } + + public int decreasePromotionStock() { + if (promotionCount == 0) return 0; + return promotionStockCount % promotionCount; + } + + public int decreaseNormalStock() { + return quantity - promotionStockCount; + } + + public int getGiftCount() { + if (promotionCount == 0) return 0; + if (isAvailableOnlyPromotion()) { + return (quantity / promotionCount); + } + return (promotionStockCount / promotionCount); + } + + public boolean canReceiveMoreFreeGift() { + if (promotionCount == 0) return false; + int remainProduct = quantity % promotionCount; + if (remainProduct == (promotionBuyCount)) { + return (promotionStockCount - quantity) >= promotionGetCount; + } + return false; + } + + public int getPromotionCount(String promotionName) throws IOException { + BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/promotions.md")); + String readPromotion; + + reader.readLine(); + + while ((readPromotion = reader.readLine()) != null) { + String[] promotionInfo = readPromotion.split(","); + if (promotionInfo[0].equals(promotionName) & isValidateDate(promotionInfo[3], promotionInfo[4])) { + promotionBuyCount = Integer.parseInt(promotionInfo[1]); + promotionGetCount = Integer.parseInt(promotionInfo[2]); + reader.close(); + return promotionBuyCount + promotionGetCount; + } + } + reader.close(); + return 0; + } + + private boolean isValidateDate(String start, String end) { + LocalDateTime targetTime = DateTimes.now(); + + String[] startInfo = start.split("-"); + String[] endInfo = end.split("-"); + + LocalDate targetDate = LocalDate.of(targetTime.getYear(), targetTime.getMonth(), targetTime.getDayOfMonth()); + LocalDate startDate = LocalDate.of(Integer.parseInt(startInfo[0]), Integer.parseInt(startInfo[1]), Integer.parseInt(startInfo[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(endInfo[0]), Integer.parseInt(endInfo[1]), Integer.parseInt(endInfo[2])); + return !targetDate.isBefore(startDate) && !targetDate.isAfter(endDate); + } + + public boolean isPromotionProduct() { + return !promotion.equals("null"); + } + public boolean isPromotionDuration(){ + return promotionCount!=0; + } + + public void increaseQuantity(int promotionGetCount) { + quantity += promotionGetCount; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPrice() { + return price; + } + + public int getPromotionStockCount() { + return promotionStockCount; + } + + public int getPromotionGetCount() { + return promotionGetCount; + } + + public int getNormalStockCount(){ + return normalStockCount; + } +}
Java
์ค‘๋ณต๋˜๋Š” ๋ฌธ๊ตฌ๋Š” ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ private static ์œผ๋กœ ์„ ์–ธํ•˜์—ฌ ๊ด€๋ฆฌ, ์‚ฌ์šฉํ•ด์ฃผ์‹œ๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,201 @@ +package store.controller; + +import store.model.Product; +import store.model.receipt.PurchaseProducts; +import store.service.ReceiptService; +import store.service.StockManageService; +import store.view.InputView; +import store.view.OutputView; + +import java.io.IOException; + +public class StoreController { + private final InputView inputView; + private final OutputView outputView; + + private boolean nextPlay; + private PurchaseProducts purchaseProducts; + private ReceiptService receiptService; + private StockManageService stockManageService; + + private int countPurchasePromotion; + private int countPurchaseNormal; + private int giftCount; + private boolean getBenefit; + + public StoreController(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + nextPlay = true; + } + + public void run() throws IOException { + while (nextPlay) { + play(); + } + } + + private void play() throws IOException { + generateService(); + stockManageService.bringStock(); + + outputView.printStoreMenu(); + repeatUntilProductAndPriceValid(); + calculateProducts(); + printReceipt(); + + if (!repeatUntilAdditionalPlayValid()) { + nextPlay = false; + } + } + + private void calculateProducts() { + for (Product product : purchaseProducts.getPurchaseProducts()) { + initCount(product); + calculateCount(product); + + stockManageService.manageStock(countPurchaseNormal, countPurchasePromotion, product); + + int stockCount = countPurchasePromotion + countPurchaseNormal; + + receiptService.make(stockCount, giftCount, product, getBenefit); + } + } + + private void calculateCount(Product product) { + if (!product.isPromotionDuration()) { //ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ด ์•„๋‹ ๋•Œ + if (product.isPromotionProduct()) { + getBenefit = false; + } + + if (product.getNormalStockCount() >= product.getQuantity()) { + countPurchaseNormal = product.getQuantity(); + return; + } + countPurchaseNormal = product.getNormalStockCount(); + countPurchasePromotion = product.getQuantity() - countPurchaseNormal; + return; + } + + if (product.isAvailableOnlyPromotion()) { + calculateCaseOne(product); + return; + } + + if (product.isSameWithQuantity()) { + calculateCaseTwo(product); + return; + } + + calculateCaseThree(product); + } + + private void calculateCaseThree(Product product) { + countPurchasePromotion = product.getPromotionStockCount(); + countPurchaseNormal = product.getQuantity() - countPurchasePromotion; + + if (product.countPromotionDisable() > 0 & product.isPromotionProduct()) { + if (!repeatUntilPurchaseValid(product)) { + countPurchasePromotion = product.buyOnlyPromotion(); + countPurchaseNormal = 0; + } + getBenefit = false; + } + } + + private void calculateCaseTwo(Product product) { + countPurchasePromotion = product.getQuantity(); + + if (product.countPromotionDisable() > 0 & product.isPromotionProduct()) { + if (!repeatUntilPurchaseValid(product)) { + countPurchasePromotion = product.buyOnlyPromotion(); + } + getBenefit = false; + } + } + + private void calculateCaseOne(Product product) { + countPurchasePromotion = product.getQuantity(); + + if (product.canReceiveMoreFreeGift()) { //ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„, ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ๊ฐ€๋Šฅ + if (repeatUntilOneMoreFreeValid(product)) { + countPurchasePromotion += product.getPromotionGetCount(); + giftCount += product.getPromotionGetCount(); + product.increaseQuantity(product.getPromotionGetCount()); + return; + } + getBenefit = false; + } + } + + private void generateService() { + receiptService = new ReceiptService(); + stockManageService = new StockManageService(); + } + + private void initCount(Product product) { + getBenefit = true; + countPurchasePromotion = 0; + countPurchaseNormal = 0; + giftCount = product.getGiftCount(); + } + + private void repeatUntilProductAndPriceValid() { + while (true) { + try { + purchaseProducts = new PurchaseProducts(inputView.getProductAndPrice()); + return; + } catch (IllegalArgumentException | IOException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilPurchaseValid(Product product) { + while (true) { + try { + return inputView.getPurchaseOrNot(product.getName(), product.countPromotionDisable()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilOneMoreFreeValid(Product product) { + while (true) { + try { + return inputView.getOneMoreFree(product); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilMembershipDiscountValid() { + while (true) { + try { + return inputView.getMembershipDiscountOrNot(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilAdditionalPlayValid() { + while (true) { + try { + return inputView.getAdditionalPurchase(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void printReceipt() throws IOException { + receiptService.calculateDiscount(repeatUntilMembershipDiscountValid()); + outputView.printPurchaseProduct(purchaseProducts); + outputView.printGiftProducts(receiptService.getGiftProducts()); + outputView.printAmountInfo(receiptService.getAmountInfo()); + stockManageService.reflectStock(); + } +}
Java
``repeatUntil`` ๋ฉ”์„œ๋“œ๊ฐ€ ๊ฐ™์€ ํŒจํ„ด์œผ๋กœ ๋ฐ˜๋ณต๋˜๊ณ  ์žˆ์–ด ์ฝ”๋“œ ์ค‘๋ณต์ด ๋งŽ๊ฒŒ ๋А๊ปด์ ธ์š”. ์ €๋„ 3์ฃผ ์ฐจ ๋กœ๋˜ ๋ฏธ์…˜ ๊ตฌํ˜„ํ•˜๋ฉด์„œ ๋ฐ˜๋ณต์„ ์–ด๋–ป๊ฒŒ ํ•˜๋ฉด ์—†์•จ ์ˆ˜ ์žˆ์„๊นŒ ๋งŽ์ด ์ฐพ์•„๋ณด๋‹ค๊ฐ€ ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ ‘ํ•˜๊ฒŒ ๋๋Š”๋ฐ์š”! [๋žŒ๋‹ค์‹, ๋ฉ”์„œ๋“œ ์ฐธ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ์˜ˆ์™ธ ๋ฐœ์ƒ์‹œ ์„ฑ๊ณตํ•  ๋•Œ ๊นŒ์ง€ ๋ฐ˜๋ณต ๊ตฌํ˜„ - ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค](https://dev-dongmoo.tistory.com/14) ์œ„ ๋ธ”๋กœ๊ทธ ํฌ์ŠคํŒ…์ด ์ฐธ๊ณ ๊ฐ€ ๋  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”โ˜บ๏ธ
@@ -0,0 +1,71 @@ +package store.model.receipt; + +import store.global.MembershipDiscount; +import store.model.Product; + +import java.text.DecimalFormat; + +public class AmountInfo { + private int totalPurchaseAmount; + private int totalPurchaseCount; + private int promotionDiscount; + private int membershipDiscount; + + public AmountInfo() { + init(); + } + + private void init() { + totalPurchaseAmount = 0; + totalPurchaseCount = 0; + promotionDiscount = 0; + membershipDiscount = 0; + } + + public void increaseTotal(int quantity, int price) { + totalPurchaseCount += quantity; + totalPurchaseAmount += quantity * price; + } + + public void calculatePromotionDiscount(Product product, int giftCount) { + promotionDiscount += product.getPrice() * giftCount; + } + + public void calculateMembershipDiscount(boolean isMembershipDiscount) { + if (!isMembershipDiscount) { + membershipDiscount = 0; + return; + } + + DecimalFormat df = new DecimalFormat("#"); + membershipDiscount = Integer.parseInt(df.format(membershipDiscount * MembershipDiscount.DISCOUNT_RATE.getValue())); + + membershipDiscount = Math.min(membershipDiscount, (int)MembershipDiscount.MAX_DISCOUNT.getValue()); + } + + public void increaseMembershipDiscount(Product product, int giftCount, boolean getBenefit) { + if (giftCount == 0 & getBenefit) { + membershipDiscount += product.getPrice() * product.getQuantity(); + } + } + + public int getPayment() { + return totalPurchaseAmount - (promotionDiscount + membershipDiscount); + } + + public int getTotalPurchaseAmount() { + return totalPurchaseAmount; + } + + public int getTotalPurchaseCount() { + return totalPurchaseCount; + } + + public int getPromotionDiscount() { + return promotionDiscount; + } + + public int getMembershipDiscount() { + return membershipDiscount; + } +}
Java
์ƒ์„ฑ์ž ๋‚ด๋ถ€์—์„œ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ฃผ์‹œ์ง€ ์•Š๊ณ  ``init()`` ๋ฉ”์„œ๋“œ๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ฃผ์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”~?
@@ -0,0 +1,71 @@ +package store.model.receipt; + +import store.global.MembershipDiscount; +import store.model.Product; + +import java.text.DecimalFormat; + +public class AmountInfo { + private int totalPurchaseAmount; + private int totalPurchaseCount; + private int promotionDiscount; + private int membershipDiscount; + + public AmountInfo() { + init(); + } + + private void init() { + totalPurchaseAmount = 0; + totalPurchaseCount = 0; + promotionDiscount = 0; + membershipDiscount = 0; + } + + public void increaseTotal(int quantity, int price) { + totalPurchaseCount += quantity; + totalPurchaseAmount += quantity * price; + } + + public void calculatePromotionDiscount(Product product, int giftCount) { + promotionDiscount += product.getPrice() * giftCount; + } + + public void calculateMembershipDiscount(boolean isMembershipDiscount) { + if (!isMembershipDiscount) { + membershipDiscount = 0; + return; + } + + DecimalFormat df = new DecimalFormat("#"); + membershipDiscount = Integer.parseInt(df.format(membershipDiscount * MembershipDiscount.DISCOUNT_RATE.getValue())); + + membershipDiscount = Math.min(membershipDiscount, (int)MembershipDiscount.MAX_DISCOUNT.getValue()); + } + + public void increaseMembershipDiscount(Product product, int giftCount, boolean getBenefit) { + if (giftCount == 0 & getBenefit) { + membershipDiscount += product.getPrice() * product.getQuantity(); + } + } + + public int getPayment() { + return totalPurchaseAmount - (promotionDiscount + membershipDiscount); + } + + public int getTotalPurchaseAmount() { + return totalPurchaseAmount; + } + + public int getTotalPurchaseCount() { + return totalPurchaseCount; + } + + public int getPromotionDiscount() { + return promotionDiscount; + } + + public int getMembershipDiscount() { + return membershipDiscount; + } +}
Java
``membershipDiscount``์— ๋Œ€ํ•œ ๊ณ„์‚ฐ ๋กœ์ง์„ ``MembershipDiscount`` Enum ๋‚ด๋ถ€๋กœ ์˜ฎ๊ธฐ๋Š” ๋ฐฉ๋ฒ•์„ ๊ณ ๋ คํ•ด๋ณด์‹œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,75 @@ +package store.view; + +import store.model.GiftProduct; +import store.model.Product; +import store.model.receipt.AmountInfo; +import store.model.receipt.GiftProducts; +import store.model.receipt.PurchaseProducts; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class OutputView { + public void printStoreMenu() throws IOException { + System.out.println(""" + ์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. + ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + """); + + BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/products.md")); + String product; + + reader.readLine(); + + while ((product = reader.readLine()) != null) { + String[] str = product.split(","); + System.out.printf("- %s %s์› %s %s", str[0], String.format("%,d", Integer.parseInt(str[1])), changeNoStock(str[2]), changeNull(str[3])); + System.out.println(); + } + reader.close(); + } + + public void printPurchaseProduct(PurchaseProducts purchaseProducts) { + System.out.println("==============W ํŽธ์˜์ ================"); + System.out.println("์ƒํ’ˆ๋ช…\t\t\t\t์ˆ˜๋Ÿ‰\t\t๊ธˆ์•ก"); + for (Product product : purchaseProducts.getPurchaseProducts()) { + System.out.printf("%-4s\t\t\t\t%s\t\t%s\n", product.getName(), product.getQuantity(), String.format("%,d", product.getQuantity() * product.getPrice())); + } + } + + public void printGiftProducts(GiftProducts giftProducts) { + System.out.println("=============์ฆ\t\t์ •==============="); + for (GiftProduct giftProduct : giftProducts.getGiftProducts()) { + System.out.printf("%-4s\t\t\t\t%d", giftProduct.getName(), giftProduct.getQuantity()); + System.out.println(); + } + } + + public void printAmountInfo(AmountInfo amountInfo) { + System.out.println("===================================="); + System.out.printf("์ด๊ตฌ๋งค์•ก\t\t\t\t%s\t\t%s", amountInfo.getTotalPurchaseCount(), String.format("%,d", amountInfo.getTotalPurchaseAmount())); + System.out.println(); + System.out.printf("ํ–‰์‚ฌํ• ์ธ\t\t\t\t\t\t%s", String.format("-%,d", amountInfo.getPromotionDiscount())); + System.out.println(); + System.out.printf("๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t\t\t\t%s", String.format("-%,d", amountInfo.getMembershipDiscount())); + System.out.println(); + System.out.printf("๋‚ด์‹ค๋ˆ\t\t\t\t\t\t%s", String.format("%,d", amountInfo.getPayment())); + System.out.println(); + } + + private String changeNull(String input) { + if (input.equals("null")) { + return ""; + } + return input; + } + + private String changeNoStock(String input) { + if (input.equals("0")) { + return "์žฌ๊ณ  ์—†์Œ"; + } + input = String.format("%,d", Integer.parseInt(input)); + return input + "๊ฐœ"; + } +}
Java
```suggestion System.out.printf("ํ–‰์‚ฌํ• ์ธ\t\t\t\t\t\t-%,d", amountInfo.getPromotionDiscount()); ``` ์ด๋ ‡๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ``System.out.printf()``์™€ ``String.format()``๋ฅผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ ๋„ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”?
@@ -1 +1,176 @@ -# java-convenience-store-precourse +## ๐Ÿ‘‰ย ์ž…๋ ฅ + +- ์ž…๋ ฅ๊ฐ’ ์ „์ฒด ๊ณตํ†ต ์˜ˆ์™ธ์ฒ˜๋ฆฌ + - [x] ๋นˆ๊ฐ’ ๋˜๋Š” null๊ฐ’ ์ž…๋ ฅ์‹œ + +- **๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰** + - ์ƒํ’ˆ๋ช…,์ˆ˜๋Ÿ‰์€ ํ•˜์ดํ”ˆ(-)์œผ๋กœ + - ๊ฐœ๋ณ„ ์ƒํ’ˆ์€ ๋Œ€๊ด„ํ˜ธ([])๋กœ ๋ฌถ์–ด ์‰ผํ‘œ(,)๋กœ ๊ตฌ๋ถ„ + - `๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])` + - ์˜ˆ์™ธ์ฒ˜๋ฆฌ + - `,`์œผ๋กœ splitํ•œ ํ›„ ๊ฐ๊ฐ์— ๋Œ€ํ•ด์„œโ€ฆ + - [x] []์ด โ€˜์–‘์ชฝ ๋์—โ€™ ๊ฐ๊ฐ ์—†์œผ๋ฉด + - [x] -์ด ์—†์œผ๋ฉด + + โ†’ ๋นˆ๋ฌธ์ž์—ด์ธ์ง€๋„ ํ•จ๊ป˜ ํ™•์ธ์ด ๊ฐ€๋Šฅ + + - -์œผ๋กœ splitํ•œ ํ›„ ๊ฐ๊ฐ์— ๋Œ€ํ•ด์„œโ€ฆ + - [x] (์Šค์Šค๋กœ ํŒ๋‹จํ•œ ๋‚ด์šฉ) ์ƒํ’ˆ ์ด๋ฆ„ ์ค‘๋ณต ์ž…๋ ฅ์‹œ + - [x] ํŒ๋งค ์ƒํ’ˆ์ด ์•„๋‹ˆ๋ฉด + - [x] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ–ˆ์œผ๋ฉด + - ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•  ๊ฒฝ์šฐ์—๋Š” ์ผ๋ฐ˜ ์žฌ๊ณ ๋ฅผ ์‚ฌ์šฉํ•จ + - [x] ์ˆ˜๋Ÿ‰์„ ์ˆซ์ž ์•„๋‹Œ ์ž๋ฃŒํ˜•์œผ๋กœ ์ž…๋ ฅํ•˜๋ฉด + - [x] ์ˆ˜๋Ÿ‰์„ 0์ดํ•˜ ์ž…๋ ฅํ•˜๋ฉด + +- Y/N ๊ณตํ†ต ์˜ˆ์™ธ์ฒ˜๋ฆฌ + - [x] `Y` ๋˜๋Š” `N` ์ด ์•„๋‹Œ ๊ฐ’์„ ์ž…๋ ฅํ–ˆ์„ ๋•Œ +- **์ฆ์ • ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์ƒํ’ˆ ์ถ”๊ฐ€ ์—ฌ๋ถ€** + - ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด ๊ณ ๊ฐ์ด ํ•ด๋‹น ์ˆ˜๋Ÿ‰๋ณด๋‹ค ์ ๊ฒŒ ๊ฐ€์ ธ์˜จ ๊ฒฝ์šฐ, + - ๊ทธ ์ˆ˜๋Ÿ‰๋งŒํผ ์ถ”๊ฐ€ ์—ฌ๋ถ€๋ฅผ ์ž…๋ ฅ๋ฐ›๊ธฐ + - `ํ˜„์žฌ {์ƒํ’ˆ๋ช…}์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)` +- **์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€์— ๋Œ€ํ•œ ์—ฌ๋ถ€** + - ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•˜์—ฌ ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์„ ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ, + - ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ์ž…๋ ฅ๋ฐ›๊ธฐ + - `ํ˜„์žฌ {์ƒํ’ˆ๋ช…} {์ˆ˜๋Ÿ‰}๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)` + - ์Šค์Šค๋กœ ํŒ๋‹จํ•œ ๋‚ด์šฉ + - `N`๋ฅผ ์ž…๋ ฅ์‹œ : ๊ตฌ๋งค๋ฅผ ์•„์˜ˆ ํ•˜์ง€ ์•Š์Œ +- **๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ ์—ฌ๋ถ€** + - `๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)` + - ๋ฉค๋ฒ„์‹ญ ํšŒ์›์€ ํ”„๋กœ๋ชจ์…˜ ๋ฏธ์ ์šฉ ๊ธˆ์•ก์˜ 30%๋ฅผ ํ• ์ธ๋ฐ›๋Š”๋‹ค. + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ํ›„ ๋‚จ์€ ๊ธˆ์•ก์— ๋Œ€ํ•ด ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ์ ์šฉํ•œ๋‹ค. + - ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์˜ ์ตœ๋Œ€ ํ•œ๋„๋Š” 8,000์›์ด๋‹ค. +- **์ถ”๊ฐ€ ๊ตฌ๋งค ์—ฌ๋ถ€** + - `๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)` + +## ๐Ÿ‘‰ย ์ถœ๋ ฅ + +- ํ™˜์˜ ์ธ์‚ฌ์™€ ํ•จ๊ป˜ ์ƒํ’ˆ๋ช…, ๊ฐ€๊ฒฉ, ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„, ์žฌ๊ณ ๋ฅผ ์•ˆ๋‚ดํ•œ๋‹ค. ๋งŒ์•ฝ ์žฌ๊ณ ๊ฐ€ 0๊ฐœ๋ผ๋ฉดย `์žฌ๊ณ  ์—†์Œ`์„ ์ถœ๋ ฅ + - **์ฒœ๋‹จ์œ„ ์‰ผํ‘œ ์ฐ๊ธฐ** + - ์˜ˆ์™ธ์ฒ˜๋ฆฌ + - ๋ชจ๋“  ์žฌ๊ณ ๊ฐ€ ์žฌ๊ณ ์—†์Œ์ด๋ฉด ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ + + ```java + ์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. + ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + + - ์ฝœ๋ผ 1,000์› 10๊ฐœ ํƒ„์‚ฐ2+1 + - ์ฝœ๋ผ 1,000์› 10๊ฐœ + - ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 + - ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ + - ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ + - ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ + - ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 + - ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ + - ๋ฌผ 500์› 10๊ฐœ + - ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ + - ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ + - ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ + - ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ + - ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ + - ์—๋„ˆ์ง€๋ฐ” 2,000์› 5๊ฐœ + - ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ + - ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ + - ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ + ``` + + +- ๊ตฌ๋งค ์ƒํ’ˆ ๋‚ด์—ญ, ์ฆ์ • ์ƒํ’ˆ ๋‚ด์—ญ, ๊ธˆ์•ก ์ •๋ณด๋ฅผ ์ถœ๋ ฅ + - **์ฒœ๋‹จ์œ„ ์‰ผํ‘œ ์ฐ๊ธฐ** + + ```java + ==============W ํŽธ์˜์ ================ + ์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก + ์ฝœ๋ผ 3 3,000 + ์—๋„ˆ์ง€๋ฐ” 5 10,000 + =============์ฆ ์ •=============== + ์ฝœ๋ผ 1 + ==================================== + ์ด๊ตฌ๋งค์•ก 8 13,000 + ํ–‰์‚ฌํ• ์ธ -1,000 + ๋ฉค๋ฒ„์‹ญํ• ์ธ -3,000 + ๋‚ด์‹ค๋ˆ 9,000 + ``` + + +- ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ + - ์‚ฌ์šฉ์ž๊ฐ€ ์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ–ˆ์„ ๋•Œ, **"[ERROR]"๋กœ ์‹œ์ž‘**ํ•˜๋Š” ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€์™€ ํ•จ๊ป˜ ์ƒํ™ฉ์— ๋งž๋Š” ์•ˆ๋‚ด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. + - ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฒฝ์šฐ:ย `[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` + - ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์„ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ:ย `[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` + - ๊ตฌ๋งค ์ˆ˜๋Ÿ‰์ด ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•œ ๊ฒฝ์šฐ:ย `[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` + - ๊ธฐํƒ€ ์ž˜๋ชป๋œ ์ž…๋ ฅ์˜ ๊ฒฝ์šฐ:ย `[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` + +- ์‚ฌ์šฉ์ž๊ฐ€ ์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ•  ๊ฒฝ์šฐย `IllegalArgumentException`๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๊ณ , "[ERROR]"๋กœ ์‹œ์ž‘ํ•˜๋Š” ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅ ํ›„ ๊ทธ ๋ถ€๋ถ„๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋‹ค์‹œ ๋ฐ›๋Š”๋‹ค. + - `Exception`์ด ์•„๋‹Œย `IllegalArgumentException`,ย `IllegalStateException`ย ๋“ฑ๊ณผ ๊ฐ™์€ ๋ช…ํ™•ํ•œ ์œ ํ˜•์„ ์ฒ˜๋ฆฌํ•œ๋‹ค. + +## ๐Ÿ‘‰ย ๋กœ์ง +- ์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ƒํ’ˆ ์ข…๋ฅ˜ 1๊ฐœ์— ๋Œ€ํ•œ ๊ตฌ๋งค ๊ฐœ์ˆ˜ = n +- n๊ณผ ๋‹ค๋ฅด๊ฒŒ ์‹ค์ œ๋กœ ์‚ฌ์šฉ์ž๊ฐ€ ๊ฐ€์ง€๊ณ  ๊ฐ€๋Š” ์ƒํ’ˆ์€ โ€œ๊ฒฐ์ œํ•œ๋‹คโ€๊ณ  ํ‘œํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค. + + +- **ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ์•„๋‹˜** โ†’ ์ผ๋ฐ˜ ์žฌ๊ณ  ์šฐ์„  ๊ฐ์†Œ + ๋‚˜๋จธ์ง€๋Š” ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๊ฐ์†Œ, + - ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ์˜ ๊ฒฝ์šฐ โ†’ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์—†์Œ + - ์ผ๋ฐ˜์žฌ๊ณ  โ‰ฅ n, ์ผ๋ฐ˜์žฌ๊ณ  < n ๋‚˜๋ˆ ์„œ ์ผ๋ฐ˜์žฌ๊ณ /ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  โ€œ๊ฒฐ์žฌโ€ํ•จ + + +- **ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„** โ†’ ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ์šฐ์„  ๊ฐ์†Œ + +- case1) ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  > n + - ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋งŒ์œผ๋กœ ์ œํ’ˆ์„ ์ถฉ๋ถ„ํžˆ ๊ตฌ๋งคํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ + - ์ด๋•Œ โ€œ๊ฒฐ์ œโ€ํ•˜๋Š” ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ์˜ ์ˆ˜๋Š” n๊ฐœ + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด, ๊ณ ๊ฐ์ด ํ•ด๋‹น ์ˆ˜๋Ÿ‰๋ณด๋‹ค ์ ๊ฒŒ ๊ฐ€์ ธ์˜จ ๊ฒฝ์šฐ + - ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ์ธ์ง€, ์ถ”๊ฐ€ ๊ฐ€๋Šฅํ•  ์ •๋„๋กœ ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ์ถฉ๋ถ„ํ•œ์ง€ ๊ฒ€์‚ฌ ํ›„, ์ถ”๊ฐ€ ์—ฌ๋ถ€ ๋ฌป๊ธฐ + - ์ถ”๊ฐ€ํ•จ โ†’ โ€œ๊ฒฐ์ œโ€ํ•˜๋Š” ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ์˜ ์ˆ˜/์ฆ์ •ํ’ˆ ์ˆ˜/๊ฒฐ์ œํ•œ ์ƒํ’ˆ์˜ ์ˆ˜๋Ÿ‰์„ ๋Š˜๋ฆผ, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ฐ›์ง€ ์•Š์Œ + - ์ถ”๊ฐ€ํ•˜์ง€ ์•Š์Œ โ†’ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ฐ›์ง€ ์•Š์Œ + + +- case2) ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  == n + - โ€œ๊ฒฐ์ œโ€ํ•ด์•ผ ํ•˜๋Š” ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ์˜ ์ˆ˜๋Š” n๊ฐœ + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด, + - ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ์ƒํ’ˆ์˜ ๊ฐœ์ˆ˜๋ผ๋ฉด + - ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ์ž…๋ ฅ๋ฐ›์Œ + - ์ •๊ฐ€ ๊ฒฐ์ œํ•˜์ง€ ์•Š์Œ โ†’ โ€œ๊ฒฐ์ œโ€ ๊ธˆ์•ก 0์›, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ฐ›์ง€ ์•Š์Œ + - ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•จ โ†’ โ€œ๊ฒฐ์ œโ€ํ•ด์•ผํ•˜๋Š” ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ์˜ ์ˆ˜ == n, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ฐ›์ง€ ์•Š์Œ + + +- case3) ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  < n + - ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•œ ๊ฒฝ์šฐ + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด, + - ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ์ƒํ’ˆ์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋‚จ์•˜๋‹ค๋ฉด + - ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ์ž…๋ ฅ๋ฐ›์Œ + - ์ •๊ฐ€ ๊ฒฐ์ œํ•˜์ง€ ์•Š์Œ โ†’ โ€œ๊ฒฐ์ œโ€ํ•ด์•ผํ•˜๋Š” ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ์˜ ์ˆ˜ == ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์ ์šฉ ๊ฐ€๋Šฅํ•œ ๊ฐœ์ˆ˜๋งŒ, ์ผ๋ฐ˜์žฌ๊ณ  โ€œ๊ฒฐ์ œโ€ ์•„๋ฌด๊ฒƒ๋„ ์•ˆํ•จ, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ฐ›์ง€ ์•Š์Œ + - ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•จ โ†’ ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๋ชจ๋‘ โ€œ๊ฒฐ์ œโ€, ๋‚˜๋จธ์ง€๋Š” ์ผ๋ฐ˜์žฌ๊ณ ์—์„œ โ€œ๊ฒฐ์ œโ€, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ฐ›์ง€ ์•Š์Œ + - ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ด ์•„๋‹Œ ๊ฒฝ์šฐ + - ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ ๋ชจ๋‘ โ€œ๊ฒฐ์ œโ€ ํ›„ ๋‚˜๋จธ์ง€๋Š” ์ผ๋ฐ˜ ์žฌ๊ณ ์—์„œ โ€œ๊ฒฐ์ œโ€, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ฐ›์Œ + + + +## ๐Ÿ‘‰ย ์ถ”๊ฐ€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ + +- `camp.nextstep.edu.missionutils`์—์„œ ์ œ๊ณตํ•˜๋Š”ย `DateTimes`ย ๋ฐย `Console`ย API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•ด์•ผ ํ•œ๋‹ค. + - ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„์„ ๊ฐ€์ ธ์˜ค๋ ค๋ฉดย `camp.nextstep.edu.missionutils.DateTimes`์˜ย `now()`๋ฅผ ํ™œ์šฉํ•œ๋‹ค. + - ์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•˜๋Š” ๊ฐ’์€ย `camp.nextstep.edu.missionutils.Console`์˜ย `readLine()`์„ ํ™œ์šฉํ•œ๋‹ค. + +- ํ…Œ์ŠคํŠธํ•  ๋•Œ `products.md` + +```java +name,price,quantity,promotion +์ฝœ๋ผ,1000,10,ํƒ„์‚ฐ2+1 +์ฝœ๋ผ,1000,10,null +์‚ฌ์ด๋‹ค,1000,8,ํƒ„์‚ฐ2+1 +์‚ฌ์ด๋‹ค,1000,7,null +์˜ค๋ Œ์ง€์ฃผ์Šค,1800,9,MD์ถ”์ฒœ์ƒํ’ˆ +์˜ค๋ Œ์ง€์ฃผ์Šค,1800,0,null +ํƒ„์‚ฐ์ˆ˜,1200,5,ํƒ„์‚ฐ2+1 +ํƒ„์‚ฐ์ˆ˜,1200,0,null +๋ฌผ,500,10,null +๋น„ํƒ€๋ฏผ์›Œํ„ฐ,1500,6,null +๊ฐ์ž์นฉ,1500,5,๋ฐ˜์งํ• ์ธ +๊ฐ์ž์นฉ,1500,5,null +์ดˆ์ฝ”๋ฐ”,1200,5,MD์ถ”์ฒœ์ƒํ’ˆ +์ดˆ์ฝ”๋ฐ”,1200,5,null +์—๋„ˆ์ง€๋ฐ”,2000,5,null +์ •์‹๋„์‹œ๋ฝ,6400,8,null +์ปต๋ผ๋ฉด,1700,1,MD์ถ”์ฒœ์ƒํ’ˆ +์ปต๋ผ๋ฉด,1700,10,null + +```
Unknown
๊ผผ๊ผผํ•˜๊ณ  ๊ฐ€๋…์„ฑ์ด ์ข‹์€ README๊ฐ€ ์ธ์ƒ์ ์ž…๋‹ˆ๋‹ค! ์ •๋ง ์ž˜ ์ •๋ฆฌํ•˜์‹  ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,67 @@ +package store.service; + +import store.model.Product; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class StockManageService { + private final List<String> foods; + + public StockManageService() { + foods = new ArrayList<>(); + } + + public void bringStock() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/products.md")); + String line; + boolean noStock = true; + + while ((line = reader.readLine()) != null) { + foods.add(line); + if (!line.split(",")[2].equals("0") & !line.split(",")[2].equals("quantity")) { + noStock = false; + } + } + reader.close(); + + if (noStock) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + public void manageStock(int countPurchaseNormal, int countPurchasePromotion, Product product) { + String targetName = product.getName(); + + for (int i = 0; i < foods.size(); i++) { + String[] food = foods.get(i).split(","); + if (food[0].equals(targetName)) { + int newStock = updateStock(food, countPurchaseNormal, countPurchasePromotion); + String updateStock = food[0] + "," + food[1] + "," + newStock + "," + food[3]; + foods.set(i, updateStock); + } + } + } + + private int updateStock(String[] food, int countPurchaseNormal, int countPurchasePromotion) { + int currentSock = Integer.parseInt(food[2]); + if (food[3].equals("null")) { + return currentSock - countPurchaseNormal; + } + return currentSock - countPurchasePromotion; + } + + public void reflectStock() throws IOException { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + + for (String updatedLine : foods) { + writer.write(updatedLine + "\r\n"); + } + writer.close(); + } +}
Java
์กฐ๊ฑด๋ฌธ์ด ์˜๋ฏธ๋ฅผ ์•Œ๊ธฐ ์–ด๋ ค์šด ๊ฑฐ ๊ฐ™์•„์š”! ๋ฉ”์„œ๋“œ๋กœ ๋ถ„๋ฆฌํ•ด๋ณด์‹œ๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,67 @@ +package store.service; + +import store.model.Product; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class StockManageService { + private final List<String> foods; + + public StockManageService() { + foods = new ArrayList<>(); + } + + public void bringStock() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/products.md")); + String line; + boolean noStock = true; + + while ((line = reader.readLine()) != null) { + foods.add(line); + if (!line.split(",")[2].equals("0") & !line.split(",")[2].equals("quantity")) { + noStock = false; + } + } + reader.close(); + + if (noStock) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); + } + } + + public void manageStock(int countPurchaseNormal, int countPurchasePromotion, Product product) { + String targetName = product.getName(); + + for (int i = 0; i < foods.size(); i++) { + String[] food = foods.get(i).split(","); + if (food[0].equals(targetName)) { + int newStock = updateStock(food, countPurchaseNormal, countPurchasePromotion); + String updateStock = food[0] + "," + food[1] + "," + newStock + "," + food[3]; + foods.set(i, updateStock); + } + } + } + + private int updateStock(String[] food, int countPurchaseNormal, int countPurchasePromotion) { + int currentSock = Integer.parseInt(food[2]); + if (food[3].equals("null")) { + return currentSock - countPurchaseNormal; + } + return currentSock - countPurchasePromotion; + } + + public void reflectStock() throws IOException { + BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/products.md", false)); + + for (String updatedLine : foods) { + writer.write(updatedLine + "\r\n"); + } + writer.close(); + } +}
Java
๋‚จ์€ ์žฌ๊ณ ๋ฅผ ๋‹ค์‹œ ํŒŒ์ผ์— ์ž‘์„ฑํ•˜์…จ๊ตฐ์š”! ์ธ์ƒ์ ์ž…๋‹ˆ๋‹ค! `CRLF(\r\n)`๋Š” ์šด์˜์ฒด์ œ์— ์ข…์†์ ์ธ ๊ฑฐ ๊ฐ™์•„์š”! `System.lineSeparator()`๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์‹œ๋Š” ๊ฑธ ์ถ”์ฒœ๋“œ๋ ค์š”!
@@ -0,0 +1,201 @@ +package store.controller; + +import store.model.Product; +import store.model.receipt.PurchaseProducts; +import store.service.ReceiptService; +import store.service.StockManageService; +import store.view.InputView; +import store.view.OutputView; + +import java.io.IOException; + +public class StoreController { + private final InputView inputView; + private final OutputView outputView; + + private boolean nextPlay; + private PurchaseProducts purchaseProducts; + private ReceiptService receiptService; + private StockManageService stockManageService; + + private int countPurchasePromotion; + private int countPurchaseNormal; + private int giftCount; + private boolean getBenefit; + + public StoreController(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + nextPlay = true; + } + + public void run() throws IOException { + while (nextPlay) { + play(); + } + } + + private void play() throws IOException { + generateService(); + stockManageService.bringStock(); + + outputView.printStoreMenu(); + repeatUntilProductAndPriceValid(); + calculateProducts(); + printReceipt(); + + if (!repeatUntilAdditionalPlayValid()) { + nextPlay = false; + } + } + + private void calculateProducts() { + for (Product product : purchaseProducts.getPurchaseProducts()) { + initCount(product); + calculateCount(product); + + stockManageService.manageStock(countPurchaseNormal, countPurchasePromotion, product); + + int stockCount = countPurchasePromotion + countPurchaseNormal; + + receiptService.make(stockCount, giftCount, product, getBenefit); + } + } + + private void calculateCount(Product product) { + if (!product.isPromotionDuration()) { //ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ด ์•„๋‹ ๋•Œ + if (product.isPromotionProduct()) { + getBenefit = false; + } + + if (product.getNormalStockCount() >= product.getQuantity()) { + countPurchaseNormal = product.getQuantity(); + return; + } + countPurchaseNormal = product.getNormalStockCount(); + countPurchasePromotion = product.getQuantity() - countPurchaseNormal; + return; + } + + if (product.isAvailableOnlyPromotion()) { + calculateCaseOne(product); + return; + } + + if (product.isSameWithQuantity()) { + calculateCaseTwo(product); + return; + } + + calculateCaseThree(product); + } + + private void calculateCaseThree(Product product) { + countPurchasePromotion = product.getPromotionStockCount(); + countPurchaseNormal = product.getQuantity() - countPurchasePromotion; + + if (product.countPromotionDisable() > 0 & product.isPromotionProduct()) { + if (!repeatUntilPurchaseValid(product)) { + countPurchasePromotion = product.buyOnlyPromotion(); + countPurchaseNormal = 0; + } + getBenefit = false; + } + } + + private void calculateCaseTwo(Product product) { + countPurchasePromotion = product.getQuantity(); + + if (product.countPromotionDisable() > 0 & product.isPromotionProduct()) { + if (!repeatUntilPurchaseValid(product)) { + countPurchasePromotion = product.buyOnlyPromotion(); + } + getBenefit = false; + } + } + + private void calculateCaseOne(Product product) { + countPurchasePromotion = product.getQuantity(); + + if (product.canReceiveMoreFreeGift()) { //ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„, ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ๊ฐ€๋Šฅ + if (repeatUntilOneMoreFreeValid(product)) { + countPurchasePromotion += product.getPromotionGetCount(); + giftCount += product.getPromotionGetCount(); + product.increaseQuantity(product.getPromotionGetCount()); + return; + } + getBenefit = false; + } + } + + private void generateService() { + receiptService = new ReceiptService(); + stockManageService = new StockManageService(); + } + + private void initCount(Product product) { + getBenefit = true; + countPurchasePromotion = 0; + countPurchaseNormal = 0; + giftCount = product.getGiftCount(); + } + + private void repeatUntilProductAndPriceValid() { + while (true) { + try { + purchaseProducts = new PurchaseProducts(inputView.getProductAndPrice()); + return; + } catch (IllegalArgumentException | IOException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilPurchaseValid(Product product) { + while (true) { + try { + return inputView.getPurchaseOrNot(product.getName(), product.countPromotionDisable()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilOneMoreFreeValid(Product product) { + while (true) { + try { + return inputView.getOneMoreFree(product); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilMembershipDiscountValid() { + while (true) { + try { + return inputView.getMembershipDiscountOrNot(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private boolean repeatUntilAdditionalPlayValid() { + while (true) { + try { + return inputView.getAdditionalPurchase(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void printReceipt() throws IOException { + receiptService.calculateDiscount(repeatUntilMembershipDiscountValid()); + outputView.printPurchaseProduct(purchaseProducts); + outputView.printGiftProducts(receiptService.getGiftProducts()); + outputView.printAmountInfo(receiptService.getAmountInfo()); + stockManageService.reflectStock(); + } +}
Java
๊ฐœ์ธ์ ์œผ๋กœ, `calculateCaseOne`, `calculateCaseTwo`, `calculateCaseThree`๋ณด๋‹ค๋Š” ์–ด๋–ค ์ผ€์ด์Šค๋ฅผ ๋‹ค๋ฃจ๋Š”์ง€ ๋ฉ”์„œ๋“œ๋ช…์— ๋ช…์‹œํ•ด์ฃผ์‹œ๋ฉด ๋” ์ง๊ด€์ ์ผ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,39 @@ +package store.model.receipt; + +import store.model.Product; + +import java.io.IOException; + +import java.util.ArrayList; +import java.util.List; + +public class PurchaseProducts { + private final List<Product> purchaseProducts; + + public PurchaseProducts(String input) throws IOException { + purchaseProducts = new ArrayList<>(); + validate(input); + } + + private void validate(String input) throws IOException { + String[] inputProducts = input.split(",", -1); + for (String product : inputProducts) { + Product pro = new Product(product); + validate(pro); + purchaseProducts.add(pro); + } + } + + private void validate(Product product){ + String target = product.getName(); + for (Product pro : purchaseProducts) { + if (pro.getName().equals(target)) { + throw new IllegalArgumentException("[ERROR] ์ค‘๋ณต๋˜๋Š” ์ƒํ’ˆ ์ด๋ฆ„์ด ์žˆ์Šต๋‹ˆ๋‹ค."); + } + } + } + + public List<Product> getPurchaseProducts() { + return purchaseProducts; + } +}
Java
์ด์ค‘ for๋ฌธ์œผ๋กœ ํ™•์ธํ•˜๋ฉด, ์‹œ๊ฐ„์ด ์ข€ ๊ฑธ๋ฆด ์ˆ˜ ์žˆ์„ ๊ฑฐ ๊ฐ™์•„์š”! `Set`์ด๋‚˜ `stream`์„ ํ™œ์šฉํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,36 @@ +package store; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EmptySource; +import org.junit.jupiter.params.provider.ValueSource; +import store.model.Product; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class ProductTest { + @DisplayName("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ œํ’ˆ ํ˜•์‹์„ ์ž…๋ ฅํ•˜๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.") + @EmptySource //null ๊ฒ€์‚ฌ๋ฅผ ํ•ด์•ผ ํ•˜๋‚˜? + @ParameterizedTest + @ValueSource(strings = {"[", "]", "[-", "-]", "[-]", "[๊ฐ์ž์นฉ-]", "[-3]",""," "}) + void throwWhenInvalidProductForm(String input) { + assertThatThrownBy(() -> new Product(input)) + .isInstanceOf(IllegalArgumentException.class); + } + + @DisplayName("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ œํ’ˆ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.") + @ParameterizedTest + @ValueSource(strings = {"[ํฌ๋ฅด์‰-3]"}) + void throwWhenInvalidProductName(String input) { + assertThatThrownBy(() -> new Product(input)) + .isInstanceOf(IllegalArgumentException.class); + } + + @DisplayName("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ œํ’ˆ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•˜๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.") + @ParameterizedTest + @ValueSource(strings = {"[๊ฐ์ž์นฉ-๊ฐ]", "[๊ฐ์ž์นฉ-0]", "[๊ฐ์ž์นฉ-1000]"}) + void throwWhenInvalidProductQuantity(String input) { + assertThatThrownBy(() -> new Product(input)) + .isInstanceOf(IllegalArgumentException.class); + } +}
Java
๊ผผ๊ผผํ•œ ํ…Œ์ŠคํŠธ๊ฐ€ ์ธ์ƒ์ ์ž…๋‹ˆ๋‹ค! ๊ฐœ์ธ์ ์œผ๋กœ, ์˜ˆ์™ธ ํ…Œ์ŠคํŠธ๋Š” ์˜ˆ์™ธ ๋ฉ”์‹œ์ง€๊นŒ์ง€ ํŒ๋ณ„ํ•ด์•ผ ๋” ์ •ํ™•ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ์˜ˆ์™ธ ๋ฉ”์‹œ์ง€๋ฅผ ์ƒ์ˆ˜ํ™”ํ•˜์‹œ๋ฉด, ํ…Œ์ŠคํŠธ์—๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์–ด์„œ ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,58 @@ +package store.view; + +import static store.global.InputConstant.BUY_PRODUCT_MESSAGE; +import static store.global.InputConstant.ENDING_MESSAGE; +import static store.global.InputConstant.MEMBERSHIP_MESSAGE; +import static store.global.InputConstant.NOTICE_FOR_FREE_STOCK; +import static store.global.InputConstant.NOTICE_FOR_FREE_STOCK_MESSAGE; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class InputView { + + private InputView() { + + } + + public static List<String> getLines(BufferedReader br) throws IOException { + List<String> lines = new ArrayList<>(); + String line; + while ((line = getLine(br)) != null) { + lines.add(line); + } + return lines; + } + + public static String getLine(BufferedReader br) throws IOException { + return br.readLine(); + } + + public static String getBuyProductMessage(Scanner sc) { + System.out.println(BUY_PRODUCT_MESSAGE); + return sc.nextLine(); + } + + public static String getMembershipMessage(Scanner sc) { + System.out.println(MEMBERSHIP_MESSAGE); + return sc.nextLine(); + } + + public static String getEndingMessage(Scanner sc) { + System.out.println(ENDING_MESSAGE); + return sc.nextLine(); + } + + public static String getMoreFreeStock(Scanner sc, String name, int freeStock) { + System.out.printf(NOTICE_FOR_FREE_STOCK_MESSAGE, name, freeStock); + return sc.nextLine(); + } + + public static String getAgreeBuyWithNoPromotion(Scanner sc, String name, int stock) { + System.out.printf(NOTICE_FOR_FREE_STOCK, name, stock); + return sc.nextLine(); + } +}
Java
`์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•˜๋Š” ๊ฐ’์€ย camp.nextstep.edu.missionutils.Console์˜ย readLine()์„ ํ™œ์šฉํ•œ๋‹ค.`๋ผ๋Š” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์š”๊ตฌ์‚ฌํ•ญ์ด ์žˆ์–ด์„œ Scanner๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,178 @@ +package store.controller; + +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuing; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.controller.product.ItemController; +import store.controller.product.PromotionItemController; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Stock; +import store.domain.Store; +import store.domain.promotion.Promotion; +import store.utils.Parser; +import store.utils.Validator; +import store.view.FileInput; +import store.view.InputView; +import store.view.OutputView; + +public class FrontController { + + private final PromotionItemController promotionItemController; + private final ItemController itemController; + private final PromotionController promotionController; + private StoreController storeController; + private ReceiptController receiptController; + + public FrontController(ItemController itemController, PromotionItemController promotionItemController, + PromotionController promotionController) { + this.promotionItemController = promotionItemController; + this.itemController = itemController; + this.promotionController = promotionController; + } + + // ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ๋ฉ”์„œ๋“œ + public void run() throws IOException { + Store store = initializeStore(); + storeController = new StoreController(itemController, store, promotionItemController); + Scanner scanner = new Scanner(System.in); + + String isContinue = YES_INPUT_BIG; + itemController.checkItems(store.getItems(), store); + + while (isUserContinuing(isContinue)) { + isContinue = processPurchaseInStore(store, scanner); + } + } + + // ์ดˆ๊ธฐํ™” ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Store initializeStore() throws IOException { + List<Promotion> promotions = getPromotions(); + List<Item> items = getItems(promotions); + return new Store(items); + } + + // ๊ตฌ๋งค ํ”„๋กœ์„ธ์Šค ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ + private String processPurchaseInStore(Store store, Scanner scanner) { + printStoreInfo(store); + + Map<String, Stock> itemAndStock = getStringStockMap(scanner, store); + String membershipInput = getMembership(scanner); + + List<Item> purchasedItems = storeController.buyProcess(itemAndStock); + + Receipt receipt = new Receipt(purchasedItems, false); + this.receiptController = new ReceiptController(receipt); + + receiptMagic(store, scanner, receipt, membershipInput); + return isContinue(scanner); + } + + // ๋ฐ˜๋ณต ํ™•์ธ ๋ฉ”์„œ๋“œ + private String isContinue(Scanner scanner) { + try { + String isContinue; + isContinue = InputView.getEndingMessage(scanner); + Validator.YesOrNoValidator(isContinue); + return isContinue; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return isContinue(scanner); + } + } + + // ์˜์ˆ˜์ฆ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private void receiptMagic(Store store, Scanner scanner, Receipt receipt, String membershipInput) { + receiptController.notifyStockForFree(store, scanner); + receiptController.notifyPurchasedInfo(store, scanner); + receipt.calculatePrice(); + + if (isUserContinuing(membershipInput)) { + receiptController.checkMembership(); + } + OutputView.printReceipt(receipt); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด ์ดˆ๊ธฐํ™” ๋ฉ”์„œ๋“œ + private List<Promotion> getPromotions() throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.PROMOTION_FILE_NAME); + List<String> promotionStrings = InputView.getLines(br); + return promotionController.setPromotions(promotionStrings); + } + + private List<Item> getItems(List<Promotion> promotions) throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.ITEM_FILE_NAME); + List<String> itemStrings = InputView.getLines(br); + return itemController.setItems(itemStrings, promotions); + } + + // ์žฌ๊ณ  ๋ฐ ๊ตฌ๋งค ํ•ญ๋ชฉ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Map<String, Stock> getStringStockMap(Scanner scanner, Store store) { + try { + Map<String, Stock> itemAndStock = getStringStockMap(scanner); + invalidStockValidator(itemAndStock, store); + return itemAndStock; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getStringStockMap(scanner, store); + } + } + + private Map<String, Stock> getStringStockMap(Scanner scanner) { + String itemInput = InputView.getBuyProductMessage(scanner); + Validator.buyInputFormatValidator(itemInput); + return getStringStockMap(itemInput); + } + + private void invalidStockValidator(Map<String, Stock> itemAndStock, Store store) { + itemAndStock.forEach((name, stock) -> { + Item item = store.findProduct(name); + Item promotionItem = store.findPromotionProduct(name); + storeController.isValidName(name); + storeController.isValidStock(stock, item, promotionItem); + }); + } + + private Map<String, Stock> getStringStockMap(String itemInput) { + List<String> splitItemInput = Parser.splitWithCommaDelimiter(itemInput); + List<String> itemNames = new ArrayList<>(); + Map<String, Stock> itemAndStock = new HashMap<>(); + + for (String itemInfo : splitItemInput) { + Parser.itemAndStockParser(itemInfo, itemAndStock); + itemNames.add(Parser.splitWithBarDelimiter(itemInfo).getFirst()); + } + Validator.duplicatedNameValidator(itemNames); + return itemAndStock; + } + + // ๋ฉค๋ฒ„์‹ญ ํ™•์ธ ๋ฉ”์„œ๋“œ + private String getMembership(Scanner scanner) { + try { + return isUseMembership(scanner); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getMembership(scanner); + } + } + + private String isUseMembership(Scanner scanner) { + String membershipInput = InputView.getMembershipMessage(scanner); + Validator.YesOrNoValidator(membershipInput); + return membershipInput; + } + + // ์Šคํ† ์–ด ์ •๋ณด ์ถœ๋ ฅ ๋ฉ”์„œ๋“œ + private void printStoreInfo(Store store) { + OutputView.printGreeting(); + OutputView.printStoreInformation(store); + } + +}
Java
์ฃผ์„์„ ๋ฉ”์„œ๋“œ๋ฅผ ์„ค๋ช…ํ•˜๊ธฐ ์œ„ํ•ด ์ถ”๊ฐ€ํ•˜์…จ๋Š”๋ฐ, ๋ฉ”์„œ๋“œ๋ช…์ด ์ด๋ฏธ ์ฃผ์„์˜ ์—ญํ• ์„ ๋Œ€์‹ ํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ฃผ์„ ์‚ฌ์šฉ์„ ์ง€์–‘ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์€ ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,178 @@ +package store.controller; + +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuing; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.controller.product.ItemController; +import store.controller.product.PromotionItemController; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Stock; +import store.domain.Store; +import store.domain.promotion.Promotion; +import store.utils.Parser; +import store.utils.Validator; +import store.view.FileInput; +import store.view.InputView; +import store.view.OutputView; + +public class FrontController { + + private final PromotionItemController promotionItemController; + private final ItemController itemController; + private final PromotionController promotionController; + private StoreController storeController; + private ReceiptController receiptController; + + public FrontController(ItemController itemController, PromotionItemController promotionItemController, + PromotionController promotionController) { + this.promotionItemController = promotionItemController; + this.itemController = itemController; + this.promotionController = promotionController; + } + + // ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ๋ฉ”์„œ๋“œ + public void run() throws IOException { + Store store = initializeStore(); + storeController = new StoreController(itemController, store, promotionItemController); + Scanner scanner = new Scanner(System.in); + + String isContinue = YES_INPUT_BIG; + itemController.checkItems(store.getItems(), store); + + while (isUserContinuing(isContinue)) { + isContinue = processPurchaseInStore(store, scanner); + } + } + + // ์ดˆ๊ธฐํ™” ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Store initializeStore() throws IOException { + List<Promotion> promotions = getPromotions(); + List<Item> items = getItems(promotions); + return new Store(items); + } + + // ๊ตฌ๋งค ํ”„๋กœ์„ธ์Šค ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ + private String processPurchaseInStore(Store store, Scanner scanner) { + printStoreInfo(store); + + Map<String, Stock> itemAndStock = getStringStockMap(scanner, store); + String membershipInput = getMembership(scanner); + + List<Item> purchasedItems = storeController.buyProcess(itemAndStock); + + Receipt receipt = new Receipt(purchasedItems, false); + this.receiptController = new ReceiptController(receipt); + + receiptMagic(store, scanner, receipt, membershipInput); + return isContinue(scanner); + } + + // ๋ฐ˜๋ณต ํ™•์ธ ๋ฉ”์„œ๋“œ + private String isContinue(Scanner scanner) { + try { + String isContinue; + isContinue = InputView.getEndingMessage(scanner); + Validator.YesOrNoValidator(isContinue); + return isContinue; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return isContinue(scanner); + } + } + + // ์˜์ˆ˜์ฆ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private void receiptMagic(Store store, Scanner scanner, Receipt receipt, String membershipInput) { + receiptController.notifyStockForFree(store, scanner); + receiptController.notifyPurchasedInfo(store, scanner); + receipt.calculatePrice(); + + if (isUserContinuing(membershipInput)) { + receiptController.checkMembership(); + } + OutputView.printReceipt(receipt); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด ์ดˆ๊ธฐํ™” ๋ฉ”์„œ๋“œ + private List<Promotion> getPromotions() throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.PROMOTION_FILE_NAME); + List<String> promotionStrings = InputView.getLines(br); + return promotionController.setPromotions(promotionStrings); + } + + private List<Item> getItems(List<Promotion> promotions) throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.ITEM_FILE_NAME); + List<String> itemStrings = InputView.getLines(br); + return itemController.setItems(itemStrings, promotions); + } + + // ์žฌ๊ณ  ๋ฐ ๊ตฌ๋งค ํ•ญ๋ชฉ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Map<String, Stock> getStringStockMap(Scanner scanner, Store store) { + try { + Map<String, Stock> itemAndStock = getStringStockMap(scanner); + invalidStockValidator(itemAndStock, store); + return itemAndStock; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getStringStockMap(scanner, store); + } + } + + private Map<String, Stock> getStringStockMap(Scanner scanner) { + String itemInput = InputView.getBuyProductMessage(scanner); + Validator.buyInputFormatValidator(itemInput); + return getStringStockMap(itemInput); + } + + private void invalidStockValidator(Map<String, Stock> itemAndStock, Store store) { + itemAndStock.forEach((name, stock) -> { + Item item = store.findProduct(name); + Item promotionItem = store.findPromotionProduct(name); + storeController.isValidName(name); + storeController.isValidStock(stock, item, promotionItem); + }); + } + + private Map<String, Stock> getStringStockMap(String itemInput) { + List<String> splitItemInput = Parser.splitWithCommaDelimiter(itemInput); + List<String> itemNames = new ArrayList<>(); + Map<String, Stock> itemAndStock = new HashMap<>(); + + for (String itemInfo : splitItemInput) { + Parser.itemAndStockParser(itemInfo, itemAndStock); + itemNames.add(Parser.splitWithBarDelimiter(itemInfo).getFirst()); + } + Validator.duplicatedNameValidator(itemNames); + return itemAndStock; + } + + // ๋ฉค๋ฒ„์‹ญ ํ™•์ธ ๋ฉ”์„œ๋“œ + private String getMembership(Scanner scanner) { + try { + return isUseMembership(scanner); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getMembership(scanner); + } + } + + private String isUseMembership(Scanner scanner) { + String membershipInput = InputView.getMembershipMessage(scanner); + Validator.YesOrNoValidator(membershipInput); + return membershipInput; + } + + // ์Šคํ† ์–ด ์ •๋ณด ์ถœ๋ ฅ ๋ฉ”์„œ๋“œ + private void printStoreInfo(Store store) { + OutputView.printGreeting(); + OutputView.printStoreInformation(store); + } + +}
Java
magic์ด๋ผ๋Š” ๋‹จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,38 @@ +package store.domain.promotion; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Promotion { + + private final String name; + private final Range range; + private final BuyGet buyGet; + + public Promotion(String name, BuyGet buyGet, Range range) { + this.buyGet = buyGet; + this.name = name; + this.range = range; + } + + public boolean checkDate(LocalDateTime now) { + LocalDate date = now.toLocalDate(); + return range.isValidRange(date); + } + + public int calculateFreeStock(int stock) { + return buyGet.calculateGetStock(stock); + } + + public int getTotalBuyStock(int totalStock, int currentStock) { + return buyGet.calculateBuyStock(totalStock, currentStock); + } + + public int getBuyStock() { + return buyGet.getBuyStock(); + } + + public String getName() { + return name; + } +}
Java
BuyGet๊ณผ Range๋กœ ๋ถ„๋ฆฌํ•œ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,151 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Store; +import store.utils.Validator; +import store.view.InputView; + +import static store.global.InputConstant.NO_INPUT_BIG; +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuingWithNo; + +public class ReceiptController { + + private final Receipt receipt; + + public ReceiptController(Receipt receipt) { + this.receipt = receipt; + } + + public void notifyStockForFree(Store store, Scanner scanner) { + List<Item> newItems = new ArrayList<>(receipt.getProducts()); + for (Item item : newItems) { + if (!item.getFree() && item.getPromotion() != null) { + isCanGetFreeStock(store, item, scanner); + } + } + } + + public void notifyPurchasedInfo(Store store, Scanner scanner) { + for (Item item : receipt.getProducts()) { + if (!item.getFree()) { + checkPromotions(scanner, store, item); + } + } + } + + public void checkMembership() { + for (Item item : receipt.getProducts()) { + if (!item.getFree()) { + Item promotionItem = receipt.findPromotionProductWithNull(item); + compareBuyGet(item, promotionItem); + } + } + } + + private void isCanGetFreeStock(Store store, Item normalItem, Scanner sc) { + Item promotionItem = receipt.findPromotionProduct(normalItem); + Item promotionItemInStore = store.findPromotionProduct(normalItem.getName()); + Item itemInStore = store.findProduct(normalItem.getName()); + if (promotionItemInStore == null) { + return; + } + + getFreeStock(normalItem, sc, promotionItem, promotionItemInStore, NO_INPUT_BIG, itemInStore); + } + + private void getFreeStock(Item normalItem, Scanner sc, Item promotionItem, Item promotionItemInStore, + String yesOrNO, + Item itemInStore) { + int moreFreeStock = getMoreFreeStock(normalItem, promotionItem, promotionItemInStore); + if (moreFreeStock > 0) { + yesOrNO = InputView.getMoreFreeStock(sc, normalItem.getName(), 1); + } + + updateStock(yesOrNO, promotionItem, promotionItemInStore, moreFreeStock, itemInStore); + } + + private int getMoreFreeStock(Item normalItem, Item promotionItem, Item promotionItemInStore) { + int currentStock = normalItem.getStockCount(); + int currentFreeStock = promotionItem.getStockCount(); + int currentPromotionStock = promotionItem.getBuyStockByFreeStock(currentFreeStock); + + return promotionItemInStore.getTotalBuyStock(currentStock - currentPromotionStock + 1, + promotionItemInStore.getStockCount()); + } + + private void updateStock(String yesOrNO, Item promotionItem, Item promotionItemInStore, int moreFreeStock, + Item itemInStore) { + if (Validator.isUserContinuing(yesOrNO)) { + promotionItem.addStock(1); + promotionItemInStore.updateStock(1 + moreFreeStock); + itemInStore.addStock(moreFreeStock); + } + } + + private void checkPromotions(Scanner sc, Store store, Item item) { + Item promotionItemInStore = store.findPromotionProduct(item.getName()); + Item freeItem = receipt.findPromotionProductWithNull(item); + + if (promotionItemInStore == null || freeItem == null) { + return; + } + + isNoPromotionItems(sc, store, item, promotionItemInStore, freeItem, YES_INPUT_BIG); + } + + private void isNoPromotionItems(Scanner sc, Store store, Item item, Item promotionItemInStore, Item freeItem, + String isPurchase) { + int getCount = promotionItemInStore.getBuyStock(); + int freeStock = freeItem.getStockCount(); + int currentBuyStockByPromotion = item.getBuyStockByFreeStock(freeStock); + int currentBuyStockWithNoPromotion = item.getStockCount() - currentBuyStockByPromotion; + + if (getCount <= currentBuyStockWithNoPromotion) { + isPurchase = InputView.getAgreeBuyWithNoPromotion(sc, item.getName(), currentBuyStockWithNoPromotion); + } + refundProcess(store, item, isPurchase, currentBuyStockWithNoPromotion); + } + + private void refundProcess(Store store, Item item, String isPurchase, int currentBuyStockWithNoPromotion) { + if (isUserContinuingWithNo(isPurchase)) { + notPurchase(store, item, currentBuyStockWithNoPromotion); + } + } + + private void notPurchase(Store store, Item item, int stock) { + Item promotionItemInStore = store.findPromotionProduct(item.getName()); + Item itemInStore = store.findProduct(item.getName()); + + stock = calculateUpdateStock(item, stock, itemInStore); + + if (stock > 0) { + promotionItemInStore.addStock(stock); + item.updateStock(stock); + } + } + + private int calculateUpdateStock(Item item, int stock, Item itemInStore) { + int totalItemInStore = itemInStore.getTotalStock(); + + int refundStock = Math.min(stock, totalItemInStore - itemInStore.getStockCount()); + itemInStore.addStock(refundStock); + item.updateStock(refundStock); + stock -= refundStock; + return stock; + } + + private void compareBuyGet(Item item, Item promotionItem) { + if (promotionItem == null) { + receipt.setMembership(true); + return; + } + if (item.getStockCount() != item.getBuyStockByFreeStock(promotionItem.getStockCount())) { + receipt.setMembership(true); + } + } +}
Java
์ œ๊ฐ€ ๋ณด๊ธฐ์— 2+1, 1+1์ฒ˜๋Ÿผ ๋ฌด์กฐ๊ฑด Get์ด 1์ธ ์ƒํ™ฉ์„ ๊ฐ€์ •ํ•˜๊ณ  currentPromotionStock + 1์„ ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ํ”„๋กœ๋ชจ์…˜์ด ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— BuyGet ํด๋ž˜์Šค์˜ get ๊ฐ’์„ ๋”ํ•ด์ฃผ๋Š” ๊ฒŒ ๋” ์ข‹์ง€ ์•Š์„๊นŒ ์‹ถ์–ด์š”!
@@ -0,0 +1,178 @@ +package store.controller; + +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuing; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.controller.product.ItemController; +import store.controller.product.PromotionItemController; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Stock; +import store.domain.Store; +import store.domain.promotion.Promotion; +import store.utils.Parser; +import store.utils.Validator; +import store.view.FileInput; +import store.view.InputView; +import store.view.OutputView; + +public class FrontController { + + private final PromotionItemController promotionItemController; + private final ItemController itemController; + private final PromotionController promotionController; + private StoreController storeController; + private ReceiptController receiptController; + + public FrontController(ItemController itemController, PromotionItemController promotionItemController, + PromotionController promotionController) { + this.promotionItemController = promotionItemController; + this.itemController = itemController; + this.promotionController = promotionController; + } + + // ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ๋ฉ”์„œ๋“œ + public void run() throws IOException { + Store store = initializeStore(); + storeController = new StoreController(itemController, store, promotionItemController); + Scanner scanner = new Scanner(System.in); + + String isContinue = YES_INPUT_BIG; + itemController.checkItems(store.getItems(), store); + + while (isUserContinuing(isContinue)) { + isContinue = processPurchaseInStore(store, scanner); + } + } + + // ์ดˆ๊ธฐํ™” ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Store initializeStore() throws IOException { + List<Promotion> promotions = getPromotions(); + List<Item> items = getItems(promotions); + return new Store(items); + } + + // ๊ตฌ๋งค ํ”„๋กœ์„ธ์Šค ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ + private String processPurchaseInStore(Store store, Scanner scanner) { + printStoreInfo(store); + + Map<String, Stock> itemAndStock = getStringStockMap(scanner, store); + String membershipInput = getMembership(scanner); + + List<Item> purchasedItems = storeController.buyProcess(itemAndStock); + + Receipt receipt = new Receipt(purchasedItems, false); + this.receiptController = new ReceiptController(receipt); + + receiptMagic(store, scanner, receipt, membershipInput); + return isContinue(scanner); + } + + // ๋ฐ˜๋ณต ํ™•์ธ ๋ฉ”์„œ๋“œ + private String isContinue(Scanner scanner) { + try { + String isContinue; + isContinue = InputView.getEndingMessage(scanner); + Validator.YesOrNoValidator(isContinue); + return isContinue; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return isContinue(scanner); + } + } + + // ์˜์ˆ˜์ฆ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private void receiptMagic(Store store, Scanner scanner, Receipt receipt, String membershipInput) { + receiptController.notifyStockForFree(store, scanner); + receiptController.notifyPurchasedInfo(store, scanner); + receipt.calculatePrice(); + + if (isUserContinuing(membershipInput)) { + receiptController.checkMembership(); + } + OutputView.printReceipt(receipt); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด ์ดˆ๊ธฐํ™” ๋ฉ”์„œ๋“œ + private List<Promotion> getPromotions() throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.PROMOTION_FILE_NAME); + List<String> promotionStrings = InputView.getLines(br); + return promotionController.setPromotions(promotionStrings); + } + + private List<Item> getItems(List<Promotion> promotions) throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.ITEM_FILE_NAME); + List<String> itemStrings = InputView.getLines(br); + return itemController.setItems(itemStrings, promotions); + } + + // ์žฌ๊ณ  ๋ฐ ๊ตฌ๋งค ํ•ญ๋ชฉ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Map<String, Stock> getStringStockMap(Scanner scanner, Store store) { + try { + Map<String, Stock> itemAndStock = getStringStockMap(scanner); + invalidStockValidator(itemAndStock, store); + return itemAndStock; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getStringStockMap(scanner, store); + } + } + + private Map<String, Stock> getStringStockMap(Scanner scanner) { + String itemInput = InputView.getBuyProductMessage(scanner); + Validator.buyInputFormatValidator(itemInput); + return getStringStockMap(itemInput); + } + + private void invalidStockValidator(Map<String, Stock> itemAndStock, Store store) { + itemAndStock.forEach((name, stock) -> { + Item item = store.findProduct(name); + Item promotionItem = store.findPromotionProduct(name); + storeController.isValidName(name); + storeController.isValidStock(stock, item, promotionItem); + }); + } + + private Map<String, Stock> getStringStockMap(String itemInput) { + List<String> splitItemInput = Parser.splitWithCommaDelimiter(itemInput); + List<String> itemNames = new ArrayList<>(); + Map<String, Stock> itemAndStock = new HashMap<>(); + + for (String itemInfo : splitItemInput) { + Parser.itemAndStockParser(itemInfo, itemAndStock); + itemNames.add(Parser.splitWithBarDelimiter(itemInfo).getFirst()); + } + Validator.duplicatedNameValidator(itemNames); + return itemAndStock; + } + + // ๋ฉค๋ฒ„์‹ญ ํ™•์ธ ๋ฉ”์„œ๋“œ + private String getMembership(Scanner scanner) { + try { + return isUseMembership(scanner); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getMembership(scanner); + } + } + + private String isUseMembership(Scanner scanner) { + String membershipInput = InputView.getMembershipMessage(scanner); + Validator.YesOrNoValidator(membershipInput); + return membershipInput; + } + + // ์Šคํ† ์–ด ์ •๋ณด ์ถœ๋ ฅ ๋ฉ”์„œ๋“œ + private void printStoreInfo(Store store) { + OutputView.printGreeting(); + OutputView.printStoreInformation(store); + } + +}
Java
์ปจํŠธ๋กค๋Ÿฌ์—์„œ Validator๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒƒ ๋ณด๋‹ค ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•ด์„œ ์—ญํ•  ๋ถ„๋‹ดํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ํฌํ›ˆ๋‹˜์˜ ์ƒ๊ฐ์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,94 @@ +package store.controller; + +import static store.domain.Item.isItemExists; +import static store.domain.Store.addPurchaseProduct; +import static store.global.ErrorMessages.INVALID_INPUT_STOCK; +import static store.global.ErrorMessages.PRODUCT_NOT_FOUND; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.controller.product.ItemController; +import store.controller.product.PromotionItemController; +import store.domain.Item; +import store.domain.Stock; +import store.domain.Store; + +public class StoreController { + + private final Store store; + private final ItemController itemController; + private final PromotionItemController promotionItemController; + + public StoreController(ItemController itemController, Store store, + PromotionItemController promotionItemController) { + this.itemController = itemController; + this.store = store; + this.promotionItemController = promotionItemController; + } + + public List<Item> buyProcess(Map<String, Stock> shoppingCarts) { + List<Item> purchasedItems = new ArrayList<>(); + + shoppingCarts.forEach((product, stock) -> { + Item nomalItem = store.findProduct(product); + Item promotionalItem = store.findPromotionProduct(product); + + isValidItemAndStock(stock, nomalItem, promotionalItem); + process(stock, promotionalItem, purchasedItems, nomalItem); + }); + return purchasedItems; + } + + public void isValidStock(Stock stock, Item promotionalItem, Item normalItem) { + int promotionStockCount = Optional.ofNullable(store.getProductStock(promotionalItem)) + .map(Stock::getStock) + .orElse(0); + int normalStockCount = Optional.ofNullable(store.getProductStock(normalItem)) + .map(Stock::getStock) + .orElse(0); + + if (promotionStockCount + normalStockCount < stock.getStock()) { + throw new IllegalArgumentException(INVALID_INPUT_STOCK.getMessage()); + } + } + + public void isValidName(String name) { + boolean flag = false; + for(Item item : store.getItems()){ + if (item.getName().equals(name)) { + flag = true; + break; + } + } + if (!flag) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND.getMessage()); + } + } + + private void process(Stock stock, Item promotionalItem, List<Item> purchasedItems, Item nomalItem) { + Item item = purchaseProcess(stock, promotionalItem, purchasedItems, nomalItem); + addPurchaseProduct(purchasedItems, item); + } + + private void isValidItemAndStock(Stock stock, Item nomalItem, Item promotionalItem) { + isItemExists(nomalItem, promotionalItem); + isValidStock(stock, promotionalItem, nomalItem); + } + + private Item purchaseProcess(Stock stock, Item promotionalItem, List<Item> purchasedItems, Item nomalItem) { + Item item = processPromotionItems(stock, promotionalItem, purchasedItems, nomalItem); + itemController.processItems(stock, item, nomalItem, purchasedItems); + return item; + } + + private Item processPromotionItems(Stock stock, Item promotionalItem, List<Item> purchasedItems, Item nomalItem) { + Item item = promotionItemController.processPromotionItem(stock, promotionalItem, purchasedItems, store); + + if (item == null) { + item = new Item(nomalItem, new Stock(0), Boolean.FALSE); + } + return item; + } +}
Java
Boolean์„ ๋ž˜ํผ ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ง€์ •ํ•ด์ค€ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,70 @@ +package store.controller.product; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; +import static store.domain.Store.addFreeProduct; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import store.domain.Item; +import store.domain.Stock; +import store.domain.Store; + +public class PromotionItemController { + + public Item processPromotionItem(Stock stock, Item promotionalItem, List<Item> purchasedItems, Store store) { + Stock stockFreeItem = new Stock(0); + Stock stockForPay = new Stock(0); + Item purchasedItem = null; + if (promotionalItem == null) { + return null; + } + if (promotionalItem.checkDate(DateTimes.now())) { + Item item = store.buyPromoItemNoDiscount(stock, promotionalItem, purchasedItems); + if (item != null) { + return item; + } + purchasedItem = processPromotionItems(stock, promotionalItem, purchasedItems, stockFreeItem, stockForPay); + } + + return purchasedItem; + } + + public static int processRemainingPromotionStock(Item promotionalItem, Stock remainStock) { + return Math.min(promotionalItem.getStockCount(), remainStock.getStock()); + } + + private Item processPromotionItems(Stock stock, Item promotionalItem, List<Item> purchasedItems, Stock stockFreeItem, + Stock stockForPay) { + Item purchasedItem; + promotionProcess(stock, promotionalItem, stockFreeItem, stockForPay); + purchasedItem = new Item(promotionalItem, stockForPay, FALSE); + addFreeProduct(stockFreeItem, promotionalItem, purchasedItems, TRUE); + return purchasedItem; + } + + private static void promotionProcess(Stock stock, Item promotionalItem, Stock stockFreeItem, Stock stockForPay) { + int stockForPromotionItem = promotionalItem.getTotalBuyStock(stock.getStock(), promotionalItem.getStockCount()); + int freeStock = promotionalItem.calculateFreeStock(stockForPromotionItem); + + updatePromotionItems(promotionalItem, stockFreeItem, stockForPay, freeStock, stockForPromotionItem); + + stock.minus(stockForPromotionItem + freeStock); + int remainingStock = updateRemainItem(stock, promotionalItem, stockForPay); + stock.minus(remainingStock); + } + + private static int updateRemainItem(Stock stock, Item promotionalItem, Stock stockForPay) { + int remainingStock = processRemainingPromotionStock(promotionalItem, stock); + promotionalItem.updateStock(remainingStock); + stockForPay.plus(remainingStock); + return remainingStock; + } + + private static void updatePromotionItems(Item promotionalItem, Stock stockFreeItem, Stock stockForPay, int freeStock, + int stockForPromotionItem) { + stockFreeItem.plus(freeStock); + stockForPay.plus(stockForPromotionItem); + promotionalItem.updateStock(stockForPromotionItem + freeStock); + } +}
Java
ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์š”๊ตฌ์‚ฌํ•ญ์— ๋ฉ”์„œ๋“œ ๋ผ์ธ ์ œ์•ฝ์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์š”๊ตฌ์‚ฌํ•ญ์€ ๋งŒ์กฑ๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,110 @@ +package store.domain; + +import java.util.List; + + +public class Receipt { + + private final List<Item> items; + private int totalPrice; + private int promotionPrice; + private boolean membership; + private int membershipPrice; + + public Receipt(List<Item> items, boolean membership) { + this.items = items; + this.membership = membership; + } + + public Item findPromotionProduct(Item promotionItem) { + for (Item item : items) { + if (item.getName().equals(promotionItem.getName()) && (item.getFree())) { + return item; + } + } + Item newItem = new Item(promotionItem, new Stock(0), true); + items.add(newItem); + return newItem; + } + + public void setMembership(boolean membership) { + this.membership = membership; + } + + public Item findPromotionProductWithNull(Item promotionItem) { + for (Item item : items) { + if (item.getName().equals(promotionItem.getName()) && (item.getPromotion() != null)) { + return item; + } + } + return null; + } + + public void calculatePrice() { + for (Item item : items) { + totalPrice += item.calculatePrice(); + if (item.getFree()) { + promotionPrice += item.calculatePrice(); + } + } + } + + public int calculateStock(Item target) { + int count = 0; + for (Item item : items) { + if (item.getName().equals(target.getName())) { + count += item.getStockCount(); + } + } + return count; + } + + public int totalStock() { + int total = 0; + for (Item item : items) { + total += item.getStockCount(); + } + return total; + } + + public boolean getMembership() { + return membership; + } + + public List<Item> getProducts() { + return items; + } + + public int getPromotionPrice() { + return promotionPrice; + } + + public int getTotalPrice() { + return totalPrice; + } + + public int getMembershipPrice() { + return membershipPrice; + } + + public Integer applyMembership() { + System.out.println(); + int discountPrice = 0; + for (Item item : items) { + if (item.getFree()) { + int buyStock = item.getBuyStockByFreeStock(item.getStockCount()); + discountPrice += buyStock * item.getPrice(); + } + } + if (getMembership()) { + return calculateMembershipPrice(discountPrice); + } + return 0; + } + + public int calculateMembershipPrice(int discountPrice) { + membershipPrice = Math.min((int) ((totalPrice - promotionPrice - discountPrice) * 0.3), 8000); + return membershipPrice; + } + +}
Java
์ด ๋ฉ”์„œ๋“œ์—์„œ ๊ฐœํ–‰์ฒ˜๋ฆฌ๋ฅผ ํ•˜๋Š” ๊ฑด ์ข‹์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๊ทธ๋ฆฌ๊ณ  ๋ฉ”์„œ๋“œ ๋ผ์ธ ์š”๊ตฌ์‚ฌํ•ญ์„ ์ง€์ผœ์•ผ ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,62 @@ +package store.domain; + +import static store.global.ErrorMessages.INVALID_STATE_ERROR; + +import java.util.Objects; + +public class Stock { + + private int stock; + + public Stock(int stock) { + validate(stock); + this.stock = stock; + } + + public int getStock() { + return stock; + } + + public boolean compare(int stock) { + return this.stock >= stock; + } + + public void minus(int stock) { + updateValidate(stock); + this.stock -= stock; + } + + public void plus(int stock) { + this.stock += stock; + } + + private void validate(int stock) { + if (stock < 0) { + throw new IllegalStateException(INVALID_STATE_ERROR.getMessage()); + } + } + + private void updateValidate(int stock) { + if (stock > this.stock) { + throw new IllegalStateException(INVALID_STATE_ERROR.getMessage()); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Stock stock1 = (Stock) o; + return stock == stock1.stock; + } + + @Override + public int hashCode() { + return Objects.hashCode(stock); + } +} +
Java
์ด ๋ถ€๋ถ„์„ ๋”ฐ๋กœ Overrideํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,25 @@ +package store.view; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class FileInput { + + private FileInput() { + + } + + public static final String ITEM_FILE_NAME = "products.md"; + public static final String PROMOTION_FILE_NAME = "promotions.md"; + + public static BufferedReader FileInputSetting(String fileName) { + InputStream inputStream = FileInput.class.getClassLoader().getResourceAsStream(fileName); + + if (inputStream == null) { + throw new IllegalStateException("File not found: products.md"); + } + + return new BufferedReader(new InputStreamReader(inputStream)); + } +}
Java
์ด ๋ถ€๋ถ„ ์˜ˆ์™ธ ๋ฉ”์„ธ์ง€์˜ ๊ฒฝ์šฐ๋„ ์ƒ์ˆ˜์—์„œ ๊ฐ€์ ธ์™€์•ผ ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,58 @@ +package store.view; + +import static store.global.InputConstant.BUY_PRODUCT_MESSAGE; +import static store.global.InputConstant.ENDING_MESSAGE; +import static store.global.InputConstant.MEMBERSHIP_MESSAGE; +import static store.global.InputConstant.NOTICE_FOR_FREE_STOCK; +import static store.global.InputConstant.NOTICE_FOR_FREE_STOCK_MESSAGE; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class InputView { + + private InputView() { + + } + + public static List<String> getLines(BufferedReader br) throws IOException { + List<String> lines = new ArrayList<>(); + String line; + while ((line = getLine(br)) != null) { + lines.add(line); + } + return lines; + } + + public static String getLine(BufferedReader br) throws IOException { + return br.readLine(); + } + + public static String getBuyProductMessage(Scanner sc) { + System.out.println(BUY_PRODUCT_MESSAGE); + return sc.nextLine(); + } + + public static String getMembershipMessage(Scanner sc) { + System.out.println(MEMBERSHIP_MESSAGE); + return sc.nextLine(); + } + + public static String getEndingMessage(Scanner sc) { + System.out.println(ENDING_MESSAGE); + return sc.nextLine(); + } + + public static String getMoreFreeStock(Scanner sc, String name, int freeStock) { + System.out.printf(NOTICE_FOR_FREE_STOCK_MESSAGE, name, freeStock); + return sc.nextLine(); + } + + public static String getAgreeBuyWithNoPromotion(Scanner sc, String name, int stock) { + System.out.printf(NOTICE_FOR_FREE_STOCK, name, stock); + return sc.nextLine(); + } +}
Java
์ œ๊ฐ€ ์ž…์ถœ๋ ฅ์„ ์ œ์ผ ๋งˆ์ง€๋ง‰์— ๊ตฌํ˜„ํ•ด์„œ ์ •์‹ ์—†์ด ๋บ๋„ค์š” ใ…œใ…œใ…œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค !!
@@ -0,0 +1,178 @@ +package store.controller; + +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuing; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.controller.product.ItemController; +import store.controller.product.PromotionItemController; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Stock; +import store.domain.Store; +import store.domain.promotion.Promotion; +import store.utils.Parser; +import store.utils.Validator; +import store.view.FileInput; +import store.view.InputView; +import store.view.OutputView; + +public class FrontController { + + private final PromotionItemController promotionItemController; + private final ItemController itemController; + private final PromotionController promotionController; + private StoreController storeController; + private ReceiptController receiptController; + + public FrontController(ItemController itemController, PromotionItemController promotionItemController, + PromotionController promotionController) { + this.promotionItemController = promotionItemController; + this.itemController = itemController; + this.promotionController = promotionController; + } + + // ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ๋ฉ”์„œ๋“œ + public void run() throws IOException { + Store store = initializeStore(); + storeController = new StoreController(itemController, store, promotionItemController); + Scanner scanner = new Scanner(System.in); + + String isContinue = YES_INPUT_BIG; + itemController.checkItems(store.getItems(), store); + + while (isUserContinuing(isContinue)) { + isContinue = processPurchaseInStore(store, scanner); + } + } + + // ์ดˆ๊ธฐํ™” ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Store initializeStore() throws IOException { + List<Promotion> promotions = getPromotions(); + List<Item> items = getItems(promotions); + return new Store(items); + } + + // ๊ตฌ๋งค ํ”„๋กœ์„ธ์Šค ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ + private String processPurchaseInStore(Store store, Scanner scanner) { + printStoreInfo(store); + + Map<String, Stock> itemAndStock = getStringStockMap(scanner, store); + String membershipInput = getMembership(scanner); + + List<Item> purchasedItems = storeController.buyProcess(itemAndStock); + + Receipt receipt = new Receipt(purchasedItems, false); + this.receiptController = new ReceiptController(receipt); + + receiptMagic(store, scanner, receipt, membershipInput); + return isContinue(scanner); + } + + // ๋ฐ˜๋ณต ํ™•์ธ ๋ฉ”์„œ๋“œ + private String isContinue(Scanner scanner) { + try { + String isContinue; + isContinue = InputView.getEndingMessage(scanner); + Validator.YesOrNoValidator(isContinue); + return isContinue; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return isContinue(scanner); + } + } + + // ์˜์ˆ˜์ฆ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private void receiptMagic(Store store, Scanner scanner, Receipt receipt, String membershipInput) { + receiptController.notifyStockForFree(store, scanner); + receiptController.notifyPurchasedInfo(store, scanner); + receipt.calculatePrice(); + + if (isUserContinuing(membershipInput)) { + receiptController.checkMembership(); + } + OutputView.printReceipt(receipt); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด ์ดˆ๊ธฐํ™” ๋ฉ”์„œ๋“œ + private List<Promotion> getPromotions() throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.PROMOTION_FILE_NAME); + List<String> promotionStrings = InputView.getLines(br); + return promotionController.setPromotions(promotionStrings); + } + + private List<Item> getItems(List<Promotion> promotions) throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.ITEM_FILE_NAME); + List<String> itemStrings = InputView.getLines(br); + return itemController.setItems(itemStrings, promotions); + } + + // ์žฌ๊ณ  ๋ฐ ๊ตฌ๋งค ํ•ญ๋ชฉ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Map<String, Stock> getStringStockMap(Scanner scanner, Store store) { + try { + Map<String, Stock> itemAndStock = getStringStockMap(scanner); + invalidStockValidator(itemAndStock, store); + return itemAndStock; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getStringStockMap(scanner, store); + } + } + + private Map<String, Stock> getStringStockMap(Scanner scanner) { + String itemInput = InputView.getBuyProductMessage(scanner); + Validator.buyInputFormatValidator(itemInput); + return getStringStockMap(itemInput); + } + + private void invalidStockValidator(Map<String, Stock> itemAndStock, Store store) { + itemAndStock.forEach((name, stock) -> { + Item item = store.findProduct(name); + Item promotionItem = store.findPromotionProduct(name); + storeController.isValidName(name); + storeController.isValidStock(stock, item, promotionItem); + }); + } + + private Map<String, Stock> getStringStockMap(String itemInput) { + List<String> splitItemInput = Parser.splitWithCommaDelimiter(itemInput); + List<String> itemNames = new ArrayList<>(); + Map<String, Stock> itemAndStock = new HashMap<>(); + + for (String itemInfo : splitItemInput) { + Parser.itemAndStockParser(itemInfo, itemAndStock); + itemNames.add(Parser.splitWithBarDelimiter(itemInfo).getFirst()); + } + Validator.duplicatedNameValidator(itemNames); + return itemAndStock; + } + + // ๋ฉค๋ฒ„์‹ญ ํ™•์ธ ๋ฉ”์„œ๋“œ + private String getMembership(Scanner scanner) { + try { + return isUseMembership(scanner); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getMembership(scanner); + } + } + + private String isUseMembership(Scanner scanner) { + String membershipInput = InputView.getMembershipMessage(scanner); + Validator.YesOrNoValidator(membershipInput); + return membershipInput; + } + + // ์Šคํ† ์–ด ์ •๋ณด ์ถœ๋ ฅ ๋ฉ”์„œ๋“œ + private void printStoreInfo(Store store) { + OutputView.printGreeting(); + OutputView.printStoreInformation(store); + } + +}
Java
๋ฉ”์„œ๋“œ๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์•„์„œ ํ๋ฆ„ ์žก๋Š” ์šฉ๋„๋กœ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š” ?
@@ -0,0 +1,178 @@ +package store.controller; + +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuing; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.controller.product.ItemController; +import store.controller.product.PromotionItemController; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Stock; +import store.domain.Store; +import store.domain.promotion.Promotion; +import store.utils.Parser; +import store.utils.Validator; +import store.view.FileInput; +import store.view.InputView; +import store.view.OutputView; + +public class FrontController { + + private final PromotionItemController promotionItemController; + private final ItemController itemController; + private final PromotionController promotionController; + private StoreController storeController; + private ReceiptController receiptController; + + public FrontController(ItemController itemController, PromotionItemController promotionItemController, + PromotionController promotionController) { + this.promotionItemController = promotionItemController; + this.itemController = itemController; + this.promotionController = promotionController; + } + + // ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ๋ฉ”์„œ๋“œ + public void run() throws IOException { + Store store = initializeStore(); + storeController = new StoreController(itemController, store, promotionItemController); + Scanner scanner = new Scanner(System.in); + + String isContinue = YES_INPUT_BIG; + itemController.checkItems(store.getItems(), store); + + while (isUserContinuing(isContinue)) { + isContinue = processPurchaseInStore(store, scanner); + } + } + + // ์ดˆ๊ธฐํ™” ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Store initializeStore() throws IOException { + List<Promotion> promotions = getPromotions(); + List<Item> items = getItems(promotions); + return new Store(items); + } + + // ๊ตฌ๋งค ํ”„๋กœ์„ธ์Šค ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ + private String processPurchaseInStore(Store store, Scanner scanner) { + printStoreInfo(store); + + Map<String, Stock> itemAndStock = getStringStockMap(scanner, store); + String membershipInput = getMembership(scanner); + + List<Item> purchasedItems = storeController.buyProcess(itemAndStock); + + Receipt receipt = new Receipt(purchasedItems, false); + this.receiptController = new ReceiptController(receipt); + + receiptMagic(store, scanner, receipt, membershipInput); + return isContinue(scanner); + } + + // ๋ฐ˜๋ณต ํ™•์ธ ๋ฉ”์„œ๋“œ + private String isContinue(Scanner scanner) { + try { + String isContinue; + isContinue = InputView.getEndingMessage(scanner); + Validator.YesOrNoValidator(isContinue); + return isContinue; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return isContinue(scanner); + } + } + + // ์˜์ˆ˜์ฆ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private void receiptMagic(Store store, Scanner scanner, Receipt receipt, String membershipInput) { + receiptController.notifyStockForFree(store, scanner); + receiptController.notifyPurchasedInfo(store, scanner); + receipt.calculatePrice(); + + if (isUserContinuing(membershipInput)) { + receiptController.checkMembership(); + } + OutputView.printReceipt(receipt); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด ์ดˆ๊ธฐํ™” ๋ฉ”์„œ๋“œ + private List<Promotion> getPromotions() throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.PROMOTION_FILE_NAME); + List<String> promotionStrings = InputView.getLines(br); + return promotionController.setPromotions(promotionStrings); + } + + private List<Item> getItems(List<Promotion> promotions) throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.ITEM_FILE_NAME); + List<String> itemStrings = InputView.getLines(br); + return itemController.setItems(itemStrings, promotions); + } + + // ์žฌ๊ณ  ๋ฐ ๊ตฌ๋งค ํ•ญ๋ชฉ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Map<String, Stock> getStringStockMap(Scanner scanner, Store store) { + try { + Map<String, Stock> itemAndStock = getStringStockMap(scanner); + invalidStockValidator(itemAndStock, store); + return itemAndStock; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getStringStockMap(scanner, store); + } + } + + private Map<String, Stock> getStringStockMap(Scanner scanner) { + String itemInput = InputView.getBuyProductMessage(scanner); + Validator.buyInputFormatValidator(itemInput); + return getStringStockMap(itemInput); + } + + private void invalidStockValidator(Map<String, Stock> itemAndStock, Store store) { + itemAndStock.forEach((name, stock) -> { + Item item = store.findProduct(name); + Item promotionItem = store.findPromotionProduct(name); + storeController.isValidName(name); + storeController.isValidStock(stock, item, promotionItem); + }); + } + + private Map<String, Stock> getStringStockMap(String itemInput) { + List<String> splitItemInput = Parser.splitWithCommaDelimiter(itemInput); + List<String> itemNames = new ArrayList<>(); + Map<String, Stock> itemAndStock = new HashMap<>(); + + for (String itemInfo : splitItemInput) { + Parser.itemAndStockParser(itemInfo, itemAndStock); + itemNames.add(Parser.splitWithBarDelimiter(itemInfo).getFirst()); + } + Validator.duplicatedNameValidator(itemNames); + return itemAndStock; + } + + // ๋ฉค๋ฒ„์‹ญ ํ™•์ธ ๋ฉ”์„œ๋“œ + private String getMembership(Scanner scanner) { + try { + return isUseMembership(scanner); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getMembership(scanner); + } + } + + private String isUseMembership(Scanner scanner) { + String membershipInput = InputView.getMembershipMessage(scanner); + Validator.YesOrNoValidator(membershipInput); + return membershipInput; + } + + // ์Šคํ† ์–ด ์ •๋ณด ์ถœ๋ ฅ ๋ฉ”์„œ๋“œ + private void printStoreInfo(Store store) { + OutputView.printGreeting(); + OutputView.printStoreInformation(store); + } + +}
Java
์•„ ์ˆ˜์ • ์˜ˆ์ •์ด์—ˆ๋Š”๋ฐ.. ๊นŒ๋จน์—ˆ์Šต๋‹ˆ๋‹ค ใ…‹ใ…‹... ์ฝ”๋”ฉํ•˜๋‹ค ๋ฉ”์„œ๋“œ ๋ช…์ด ์ƒ๊ฐ์ด ์•ˆ๋‚˜์„œ ์ž„์˜๋กœ ์ž‘์„ฑํ•ด๋‘” ๊ฒƒ์ด์—์š”
@@ -0,0 +1,38 @@ +package store.domain.promotion; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Promotion { + + private final String name; + private final Range range; + private final BuyGet buyGet; + + public Promotion(String name, BuyGet buyGet, Range range) { + this.buyGet = buyGet; + this.name = name; + this.range = range; + } + + public boolean checkDate(LocalDateTime now) { + LocalDate date = now.toLocalDate(); + return range.isValidRange(date); + } + + public int calculateFreeStock(int stock) { + return buyGet.calculateGetStock(stock); + } + + public int getTotalBuyStock(int totalStock, int currentStock) { + return buyGet.calculateBuyStock(totalStock, currentStock); + } + + public int getBuyStock() { + return buyGet.getBuyStock(); + } + + public String getName() { + return name; + } +}
Java
์ˆ˜์ •์ด ์žฆ์€ ํ•„๋“œ๊ฐ€ ์ด๊ณ , ํ•„๋“œ๋ฅผ ๋ฉ”์„œ๋“œ๋งˆ๋‹ค ๊ณ„์† ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์ด ๋น„ํšจ์œจ์ ์ด๋ผ๊ณ  ๋А๊ปด์„œ ํ•„๋“œ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค์–ด ํ•„๋“œ์˜ ์ˆ˜์ •๊ณผ ๊ด€๋ฆฌ๋ฅผ ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ํ•˜๊ณ  ์ธ์ž๋กœ ์ „๋‹ฌ ์•ˆํ•ด๋„ ๋˜๊ฒŒ ํ–ˆ์–ด์š” !
@@ -0,0 +1,151 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Store; +import store.utils.Validator; +import store.view.InputView; + +import static store.global.InputConstant.NO_INPUT_BIG; +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuingWithNo; + +public class ReceiptController { + + private final Receipt receipt; + + public ReceiptController(Receipt receipt) { + this.receipt = receipt; + } + + public void notifyStockForFree(Store store, Scanner scanner) { + List<Item> newItems = new ArrayList<>(receipt.getProducts()); + for (Item item : newItems) { + if (!item.getFree() && item.getPromotion() != null) { + isCanGetFreeStock(store, item, scanner); + } + } + } + + public void notifyPurchasedInfo(Store store, Scanner scanner) { + for (Item item : receipt.getProducts()) { + if (!item.getFree()) { + checkPromotions(scanner, store, item); + } + } + } + + public void checkMembership() { + for (Item item : receipt.getProducts()) { + if (!item.getFree()) { + Item promotionItem = receipt.findPromotionProductWithNull(item); + compareBuyGet(item, promotionItem); + } + } + } + + private void isCanGetFreeStock(Store store, Item normalItem, Scanner sc) { + Item promotionItem = receipt.findPromotionProduct(normalItem); + Item promotionItemInStore = store.findPromotionProduct(normalItem.getName()); + Item itemInStore = store.findProduct(normalItem.getName()); + if (promotionItemInStore == null) { + return; + } + + getFreeStock(normalItem, sc, promotionItem, promotionItemInStore, NO_INPUT_BIG, itemInStore); + } + + private void getFreeStock(Item normalItem, Scanner sc, Item promotionItem, Item promotionItemInStore, + String yesOrNO, + Item itemInStore) { + int moreFreeStock = getMoreFreeStock(normalItem, promotionItem, promotionItemInStore); + if (moreFreeStock > 0) { + yesOrNO = InputView.getMoreFreeStock(sc, normalItem.getName(), 1); + } + + updateStock(yesOrNO, promotionItem, promotionItemInStore, moreFreeStock, itemInStore); + } + + private int getMoreFreeStock(Item normalItem, Item promotionItem, Item promotionItemInStore) { + int currentStock = normalItem.getStockCount(); + int currentFreeStock = promotionItem.getStockCount(); + int currentPromotionStock = promotionItem.getBuyStockByFreeStock(currentFreeStock); + + return promotionItemInStore.getTotalBuyStock(currentStock - currentPromotionStock + 1, + promotionItemInStore.getStockCount()); + } + + private void updateStock(String yesOrNO, Item promotionItem, Item promotionItemInStore, int moreFreeStock, + Item itemInStore) { + if (Validator.isUserContinuing(yesOrNO)) { + promotionItem.addStock(1); + promotionItemInStore.updateStock(1 + moreFreeStock); + itemInStore.addStock(moreFreeStock); + } + } + + private void checkPromotions(Scanner sc, Store store, Item item) { + Item promotionItemInStore = store.findPromotionProduct(item.getName()); + Item freeItem = receipt.findPromotionProductWithNull(item); + + if (promotionItemInStore == null || freeItem == null) { + return; + } + + isNoPromotionItems(sc, store, item, promotionItemInStore, freeItem, YES_INPUT_BIG); + } + + private void isNoPromotionItems(Scanner sc, Store store, Item item, Item promotionItemInStore, Item freeItem, + String isPurchase) { + int getCount = promotionItemInStore.getBuyStock(); + int freeStock = freeItem.getStockCount(); + int currentBuyStockByPromotion = item.getBuyStockByFreeStock(freeStock); + int currentBuyStockWithNoPromotion = item.getStockCount() - currentBuyStockByPromotion; + + if (getCount <= currentBuyStockWithNoPromotion) { + isPurchase = InputView.getAgreeBuyWithNoPromotion(sc, item.getName(), currentBuyStockWithNoPromotion); + } + refundProcess(store, item, isPurchase, currentBuyStockWithNoPromotion); + } + + private void refundProcess(Store store, Item item, String isPurchase, int currentBuyStockWithNoPromotion) { + if (isUserContinuingWithNo(isPurchase)) { + notPurchase(store, item, currentBuyStockWithNoPromotion); + } + } + + private void notPurchase(Store store, Item item, int stock) { + Item promotionItemInStore = store.findPromotionProduct(item.getName()); + Item itemInStore = store.findProduct(item.getName()); + + stock = calculateUpdateStock(item, stock, itemInStore); + + if (stock > 0) { + promotionItemInStore.addStock(stock); + item.updateStock(stock); + } + } + + private int calculateUpdateStock(Item item, int stock, Item itemInStore) { + int totalItemInStore = itemInStore.getTotalStock(); + + int refundStock = Math.min(stock, totalItemInStore - itemInStore.getStockCount()); + itemInStore.addStock(refundStock); + item.updateStock(refundStock); + stock -= refundStock; + return stock; + } + + private void compareBuyGet(Item item, Item promotionItem) { + if (promotionItem == null) { + receipt.setMembership(true); + return; + } + if (item.getStockCount() != item.getBuyStockByFreeStock(promotionItem.getStockCount())) { + receipt.setMembership(true); + } + } +}
Java
๋งž์Šต๋‹ˆ๋‹ค ! ๊ณผ์ œ ์š”๊ตฌ์‚ฌํ•ญ ๋ณด๋‹ค๊ฐ€ ์ž„์‹œ์ ์œผ๋กœ ํ•ด๋‘” ๊ฒƒ์„ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š์•˜๋„ค์š”.. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,70 @@ +package store.controller.product; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; +import static store.domain.Store.addFreeProduct; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import store.domain.Item; +import store.domain.Stock; +import store.domain.Store; + +public class PromotionItemController { + + public Item processPromotionItem(Stock stock, Item promotionalItem, List<Item> purchasedItems, Store store) { + Stock stockFreeItem = new Stock(0); + Stock stockForPay = new Stock(0); + Item purchasedItem = null; + if (promotionalItem == null) { + return null; + } + if (promotionalItem.checkDate(DateTimes.now())) { + Item item = store.buyPromoItemNoDiscount(stock, promotionalItem, purchasedItems); + if (item != null) { + return item; + } + purchasedItem = processPromotionItems(stock, promotionalItem, purchasedItems, stockFreeItem, stockForPay); + } + + return purchasedItem; + } + + public static int processRemainingPromotionStock(Item promotionalItem, Stock remainStock) { + return Math.min(promotionalItem.getStockCount(), remainStock.getStock()); + } + + private Item processPromotionItems(Stock stock, Item promotionalItem, List<Item> purchasedItems, Stock stockFreeItem, + Stock stockForPay) { + Item purchasedItem; + promotionProcess(stock, promotionalItem, stockFreeItem, stockForPay); + purchasedItem = new Item(promotionalItem, stockForPay, FALSE); + addFreeProduct(stockFreeItem, promotionalItem, purchasedItems, TRUE); + return purchasedItem; + } + + private static void promotionProcess(Stock stock, Item promotionalItem, Stock stockFreeItem, Stock stockForPay) { + int stockForPromotionItem = promotionalItem.getTotalBuyStock(stock.getStock(), promotionalItem.getStockCount()); + int freeStock = promotionalItem.calculateFreeStock(stockForPromotionItem); + + updatePromotionItems(promotionalItem, stockFreeItem, stockForPay, freeStock, stockForPromotionItem); + + stock.minus(stockForPromotionItem + freeStock); + int remainingStock = updateRemainItem(stock, promotionalItem, stockForPay); + stock.minus(remainingStock); + } + + private static int updateRemainItem(Stock stock, Item promotionalItem, Stock stockForPay) { + int remainingStock = processRemainingPromotionStock(promotionalItem, stock); + promotionalItem.updateStock(remainingStock); + stockForPay.plus(remainingStock); + return remainingStock; + } + + private static void updatePromotionItems(Item promotionalItem, Stock stockFreeItem, Stock stockForPay, int freeStock, + int stockForPromotionItem) { + stockFreeItem.plus(freeStock); + stockForPay.plus(stockForPromotionItem); + promotionalItem.updateStock(stockForPromotionItem + freeStock); + } +}
Java
ํ•ญ์ƒ ์„ธ์„ธํžˆ ๋ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค..ใ…Žใ…Ž ์ฒดํฌ์„ ๋ชปํ–ˆ๋„ค์š”.. ใ… ใ… ใ… 
@@ -0,0 +1,62 @@ +package store.domain; + +import static store.global.ErrorMessages.INVALID_STATE_ERROR; + +import java.util.Objects; + +public class Stock { + + private int stock; + + public Stock(int stock) { + validate(stock); + this.stock = stock; + } + + public int getStock() { + return stock; + } + + public boolean compare(int stock) { + return this.stock >= stock; + } + + public void minus(int stock) { + updateValidate(stock); + this.stock -= stock; + } + + public void plus(int stock) { + this.stock += stock; + } + + private void validate(int stock) { + if (stock < 0) { + throw new IllegalStateException(INVALID_STATE_ERROR.getMessage()); + } + } + + private void updateValidate(int stock) { + if (stock > this.stock) { + throw new IllegalStateException(INVALID_STATE_ERROR.getMessage()); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Stock stock1 = (Stock) o; + return stock == stock1.stock; + } + + @Override + public int hashCode() { + return Objects.hashCode(stock); + } +} +
Java
ํ…Œ์ŠคํŠธ๋ฅผ ์œ„ํ•ด Overrideํ•œ๊ฑด๋ฐ ๋ƒ…๋‘ฌ์•ผํ• ์ง€ ํ…Œ์ŠคํŠธ๋ฅผ ๊ณ ์ณค์–ด์•ผํ• ์ง€ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ๋‚จ๊ฒจ๋’€์Šต๋‹ˆ๋‹ค !
@@ -0,0 +1,178 @@ +package store.controller; + +import static store.global.InputConstant.YES_INPUT_BIG; +import static store.utils.Validator.isUserContinuing; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.controller.product.ItemController; +import store.controller.product.PromotionItemController; +import store.domain.Item; +import store.domain.Receipt; +import store.domain.Stock; +import store.domain.Store; +import store.domain.promotion.Promotion; +import store.utils.Parser; +import store.utils.Validator; +import store.view.FileInput; +import store.view.InputView; +import store.view.OutputView; + +public class FrontController { + + private final PromotionItemController promotionItemController; + private final ItemController itemController; + private final PromotionController promotionController; + private StoreController storeController; + private ReceiptController receiptController; + + public FrontController(ItemController itemController, PromotionItemController promotionItemController, + PromotionController promotionController) { + this.promotionItemController = promotionItemController; + this.itemController = itemController; + this.promotionController = promotionController; + } + + // ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ๋ฉ”์„œ๋“œ + public void run() throws IOException { + Store store = initializeStore(); + storeController = new StoreController(itemController, store, promotionItemController); + Scanner scanner = new Scanner(System.in); + + String isContinue = YES_INPUT_BIG; + itemController.checkItems(store.getItems(), store); + + while (isUserContinuing(isContinue)) { + isContinue = processPurchaseInStore(store, scanner); + } + } + + // ์ดˆ๊ธฐํ™” ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Store initializeStore() throws IOException { + List<Promotion> promotions = getPromotions(); + List<Item> items = getItems(promotions); + return new Store(items); + } + + // ๊ตฌ๋งค ํ”„๋กœ์„ธ์Šค ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ + private String processPurchaseInStore(Store store, Scanner scanner) { + printStoreInfo(store); + + Map<String, Stock> itemAndStock = getStringStockMap(scanner, store); + String membershipInput = getMembership(scanner); + + List<Item> purchasedItems = storeController.buyProcess(itemAndStock); + + Receipt receipt = new Receipt(purchasedItems, false); + this.receiptController = new ReceiptController(receipt); + + receiptMagic(store, scanner, receipt, membershipInput); + return isContinue(scanner); + } + + // ๋ฐ˜๋ณต ํ™•์ธ ๋ฉ”์„œ๋“œ + private String isContinue(Scanner scanner) { + try { + String isContinue; + isContinue = InputView.getEndingMessage(scanner); + Validator.YesOrNoValidator(isContinue); + return isContinue; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return isContinue(scanner); + } + } + + // ์˜์ˆ˜์ฆ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private void receiptMagic(Store store, Scanner scanner, Receipt receipt, String membershipInput) { + receiptController.notifyStockForFree(store, scanner); + receiptController.notifyPurchasedInfo(store, scanner); + receipt.calculatePrice(); + + if (isUserContinuing(membershipInput)) { + receiptController.checkMembership(); + } + OutputView.printReceipt(receipt); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด ์ดˆ๊ธฐํ™” ๋ฉ”์„œ๋“œ + private List<Promotion> getPromotions() throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.PROMOTION_FILE_NAME); + List<String> promotionStrings = InputView.getLines(br); + return promotionController.setPromotions(promotionStrings); + } + + private List<Item> getItems(List<Promotion> promotions) throws IOException { + BufferedReader br = FileInput.FileInputSetting(FileInput.ITEM_FILE_NAME); + List<String> itemStrings = InputView.getLines(br); + return itemController.setItems(itemStrings, promotions); + } + + // ์žฌ๊ณ  ๋ฐ ๊ตฌ๋งค ํ•ญ๋ชฉ ๊ด€๋ จ ๋ฉ”์„œ๋“œ + private Map<String, Stock> getStringStockMap(Scanner scanner, Store store) { + try { + Map<String, Stock> itemAndStock = getStringStockMap(scanner); + invalidStockValidator(itemAndStock, store); + return itemAndStock; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getStringStockMap(scanner, store); + } + } + + private Map<String, Stock> getStringStockMap(Scanner scanner) { + String itemInput = InputView.getBuyProductMessage(scanner); + Validator.buyInputFormatValidator(itemInput); + return getStringStockMap(itemInput); + } + + private void invalidStockValidator(Map<String, Stock> itemAndStock, Store store) { + itemAndStock.forEach((name, stock) -> { + Item item = store.findProduct(name); + Item promotionItem = store.findPromotionProduct(name); + storeController.isValidName(name); + storeController.isValidStock(stock, item, promotionItem); + }); + } + + private Map<String, Stock> getStringStockMap(String itemInput) { + List<String> splitItemInput = Parser.splitWithCommaDelimiter(itemInput); + List<String> itemNames = new ArrayList<>(); + Map<String, Stock> itemAndStock = new HashMap<>(); + + for (String itemInfo : splitItemInput) { + Parser.itemAndStockParser(itemInfo, itemAndStock); + itemNames.add(Parser.splitWithBarDelimiter(itemInfo).getFirst()); + } + Validator.duplicatedNameValidator(itemNames); + return itemAndStock; + } + + // ๋ฉค๋ฒ„์‹ญ ํ™•์ธ ๋ฉ”์„œ๋“œ + private String getMembership(Scanner scanner) { + try { + return isUseMembership(scanner); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return getMembership(scanner); + } + } + + private String isUseMembership(Scanner scanner) { + String membershipInput = InputView.getMembershipMessage(scanner); + Validator.YesOrNoValidator(membershipInput); + return membershipInput; + } + + // ์Šคํ† ์–ด ์ •๋ณด ์ถœ๋ ฅ ๋ฉ”์„œ๋“œ + private void printStoreInfo(Store store) { + OutputView.printGreeting(); + OutputView.printStoreInformation(store); + } + +}
Java
์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๊ทธ๋Ÿฌ๋ฉด ๋” ์„ธ๋ถ€์ ์œผ๋กœ ๋‚˜๋ˆ ์„œ ๊ตฌํ˜„ํ–ˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,12 @@ +package store.common; + +public class ConsoleMessages { + public static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."; + public static final String PRODUCT_LIST_HEADER = "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String PURCHASE_ITEMS_PROMPT = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String ADDITIONAL_PROMO_PROMPT = "ํ˜„์žฌ %s์€(๋Š”) %d๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String FULL_PRICE_PURCHASE_PROMPT = "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String MEMBERSHIP_DISCOUNT_PROMPT = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String ADDITIONAL_PURCHASE_PROMPT = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + public static final String LINE_SEPARATOR = System.lineSeparator(); +}
Java
enum์ด ์•„๋‹Œ class๋กœ ๊ด€๋ฆฌํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,90 @@ +package store.controller; + +import java.util.List; +import store.domain.Cart; +import store.domain.Membership; +import store.domain.ParsedItem; +import store.domain.Receipt; +import store.io.input.StoreInput; +import store.io.output.StoreOutput; +import store.service.ConvenienceStoreService; + +public class ConvenienceStoreController { + private final StoreInput storeInput; + private final StoreOutput storeOutput; + private final ConvenienceStoreService convenienceStoreService; + + public ConvenienceStoreController(StoreInput storeInput, StoreOutput storeOutput, + ConvenienceStoreService convenienceStoreService) { + this.storeInput = storeInput; + this.storeOutput = storeOutput; + this.convenienceStoreService = convenienceStoreService; + } + + public void start() { + boolean continueShopping; + try { + do { + executeShoppingCycle(); + continueShopping = getValidAdditionalPurchaseResponse(); + } while (continueShopping); + } finally { + storeOutput.close(); + } + } + + private void executeShoppingCycle() { + convenienceStoreService.printInventoryProductList(storeOutput); + + List<ParsedItem> parsedItems = getValidParsedItems(); + Cart cart = convenienceStoreService.createCart(parsedItems); + + convenienceStoreService.applyPromotionToCartItems(cart, storeInput); + + Membership membership = getValidMembershipResponse(); + + Receipt receipt = convenienceStoreService.createReceipt(cart); + storeOutput.printReceipt(receipt, cart, membership); + + updateInventory(cart); + } + + private List<ParsedItem> getValidParsedItems() { + while (true) { + try { + String input = storeInput.getPurchaseItemsInput(); + return convenienceStoreService.parseItems(input); + } catch (IllegalArgumentException | IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private Membership getValidMembershipResponse() { + while (true) { + try { + return convenienceStoreService.determineMembership(storeInput); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private void updateInventory(Cart cart) { + try { + convenienceStoreService.updateInventory(cart); + } catch (IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + + private boolean getValidAdditionalPurchaseResponse() { + while (true) { + try { + return storeInput.askForAdditionalPurchase(); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } +}
Java
ํ•ด๋‹น ํ•จ์ˆ˜๊ฐ€ `ํ•จ์ˆ˜ ๋‚ด๋ถ€๊ฐ€ 10๋ผ์ธ ์ดํ•˜`๋ผ๋Š” ๊ธฐ์ค€์„ ์ง€ํ‚ค์ง€ ์•Š๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,90 @@ +package store.controller; + +import java.util.List; +import store.domain.Cart; +import store.domain.Membership; +import store.domain.ParsedItem; +import store.domain.Receipt; +import store.io.input.StoreInput; +import store.io.output.StoreOutput; +import store.service.ConvenienceStoreService; + +public class ConvenienceStoreController { + private final StoreInput storeInput; + private final StoreOutput storeOutput; + private final ConvenienceStoreService convenienceStoreService; + + public ConvenienceStoreController(StoreInput storeInput, StoreOutput storeOutput, + ConvenienceStoreService convenienceStoreService) { + this.storeInput = storeInput; + this.storeOutput = storeOutput; + this.convenienceStoreService = convenienceStoreService; + } + + public void start() { + boolean continueShopping; + try { + do { + executeShoppingCycle(); + continueShopping = getValidAdditionalPurchaseResponse(); + } while (continueShopping); + } finally { + storeOutput.close(); + } + } + + private void executeShoppingCycle() { + convenienceStoreService.printInventoryProductList(storeOutput); + + List<ParsedItem> parsedItems = getValidParsedItems(); + Cart cart = convenienceStoreService.createCart(parsedItems); + + convenienceStoreService.applyPromotionToCartItems(cart, storeInput); + + Membership membership = getValidMembershipResponse(); + + Receipt receipt = convenienceStoreService.createReceipt(cart); + storeOutput.printReceipt(receipt, cart, membership); + + updateInventory(cart); + } + + private List<ParsedItem> getValidParsedItems() { + while (true) { + try { + String input = storeInput.getPurchaseItemsInput(); + return convenienceStoreService.parseItems(input); + } catch (IllegalArgumentException | IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private Membership getValidMembershipResponse() { + while (true) { + try { + return convenienceStoreService.determineMembership(storeInput); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private void updateInventory(Cart cart) { + try { + convenienceStoreService.updateInventory(cart); + } catch (IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + + private boolean getValidAdditionalPurchaseResponse() { + while (true) { + try { + return storeInput.askForAdditionalPurchase(); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } +}
Java
while + try-catch๊ฐ€ ๋ฐ˜๋ณต๋˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ์ด๋ฅผ ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์–ด ์ฒ˜๋ฆฌํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,135 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; + +public class CartItem { + private static final int DEFAULT_FREE_QUANTITY = 0; + private static final int MINIMUM_VALID_QUANTITY = 0; + + private final Product product; + private final int quantity; + + public CartItem(Product product, int quantity) { + this.product = product; + this.quantity = quantity; + } + + public Money calculateTotalPrice() { + return product.calculateTotalPrice(quantity); + } + + public int calculatePromotionDiscount() { + if (!product.isPromotionValid()) { + return 0; + } + Money totalAmount = calculateTotalPrice(); + Money amountWithoutPromotion = getTotalAmountWithoutPromotion(); + return totalAmount.subtract(amountWithoutPromotion).getAmount(); + } + + public int calculateTotalIfNoPromotion() { + if (!product.isPromotionValid()) { + return calculateTotalPrice().getAmount(); + } + return 0; + } + + public Money getTotalAmountWithoutPromotion() { + return product.calculatePrice(getEffectivePaidQuantity()); + } + + public int getEffectivePaidQuantity() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return quantity; + } + return calculateQuotient(promotion); + } + + private int calculateQuotient(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + return quantity - Math.min(quantity / totalRequired, product.getStock() / totalRequired); + } + + public boolean isPromotionValid() { + Promotion promotion = product.getPromotion(); + return isPromotionValid(promotion); + } + + private boolean isPromotionValid(Promotion promotion) { + return promotion != null && promotion.isValid(DateTimes.now().toLocalDate()); + } + + public boolean checkPromotionStock() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return false; + } + return isStockAvailable(promotion); + } + + private boolean isStockAvailable(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int promoAvailableQuantity = (product.getStock() / totalRequired) * totalRequired; + return (quantity - promoAvailableQuantity) > MINIMUM_VALID_QUANTITY; + } + + public int getFreeQuantity() { + Promotion promotion = product.getPromotion(); + if (promotion == null) { + return DEFAULT_FREE_QUANTITY; + } + return promotion.calculateFreeItems(quantity, product.getStock()); + } + + public int calculateRemainingQuantity() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return quantity; + } + return calculateRemainingQuantityForValidPromotion(promotion); + } + + private int calculateRemainingQuantityForValidPromotion(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int promoAvailableQuantity = (product.getStock() / totalRequired) * totalRequired; + return Math.max(MINIMUM_VALID_QUANTITY, quantity - promoAvailableQuantity); + } + + public int calculateAdditionalQuantityNeeded() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return DEFAULT_FREE_QUANTITY; + } + return calculateAdditionalQuantity(promotion); + } + + private int calculateAdditionalQuantity(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int remainder = quantity % totalRequired; + if (remainder == promotion.getBuyQuantity()) { + return totalRequired - remainder; + } + return DEFAULT_FREE_QUANTITY; + } + + public CartItem withUpdatedQuantityForFullPrice(int newQuantity) { + return new CartItem(this.product, newQuantity); + } + + public CartItem withAdditionalQuantity(int additionalQuantity) { + return new CartItem(this.product, this.quantity + additionalQuantity); + } + + public String getProductName() { + return product.getName(); + } + + public Product getProduct() { + return product; + } + + public int getQuantity() { + return quantity; + } +}
Java
CartItem์ด ๋‹ค์–‘ํ•œ ์—ญํ• ์„ ํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ”„๋กœ๋ชจ์…˜๊ณผ ๊ด€๋ จ๋œ ๋กœ์ง์€ ํ”„๋กœ๋ชจ์…˜์œผ๋กœ, ์žฌ๊ณ ๊ด€๋ฆฌ์™€ ๊ด€๋ จ๋œ ๋กœ์ง์€ ์žฌ๊ณ ๋กœ ์˜ฎ๊ฒจ ๋ณด๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,238 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.common.ErrorMessages; +import store.io.output.StoreOutput; + +public class Inventory { + private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String MD_FILE_DELIMITER = ","; + + private static final int NAME_INDEX = 0; + private static final int BUY_QUANTITY_INDEX = 1; + private static final int FREE_QUANTITY_INDEX = 2; + private static final int START_DATE_INDEX = 3; + private static final int END_DATE_INDEX = 4; + private static final int PRICE_INDEX = 1; + private static final int STOCK_INDEX = 2; + private static final int PROMOTION_NAME_INDEX = 3; + + private static final int DEFAULT_STOCK = 0; + private static final int EMPTY_PROMOTION = 0; + + private final List<Product> products = new ArrayList<>(); + private final Map<String, Promotion> promotions = new HashMap<>(); + + public Inventory() { + loadPromotions(); + loadProducts(); + } + + private void loadPromotions() { + LocalDate currentDate = DateTimes.now().toLocalDate(); + try (BufferedReader reader = new BufferedReader(new FileReader(PROMOTIONS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Promotion promotion = parsePromotion(line); + addPromotionToMap(promotion, currentDate); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PROMOTIONS_FILE); + } + } + + private Promotion parsePromotion(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int buyQuantity = Integer.parseInt(fields[BUY_QUANTITY_INDEX]); + int freeQuantity = Integer.parseInt(fields[FREE_QUANTITY_INDEX]); + LocalDate startDate = LocalDate.parse(fields[START_DATE_INDEX]); + LocalDate endDate = LocalDate.parse(fields[END_DATE_INDEX]); + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } + + private void addPromotionToMap(Promotion promotion, LocalDate currentDate) { + if (!promotion.isValid(currentDate)) { + promotions.put(promotion.getName(), null); + return; + } + promotions.put(promotion.getName(), promotion); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Product product = parseProduct(line); + addProductToInventory(product); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PRODUCTS_FILE); + } + } + + private Product parseProduct(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int price = Integer.parseInt(fields[PRICE_INDEX]); + int stock = Integer.parseInt(fields[STOCK_INDEX]); + + String promotionName = null; + if (fields.length > PROMOTION_NAME_INDEX) { + promotionName = fields[PROMOTION_NAME_INDEX]; + } + + Promotion promotion = promotions.get(promotionName); + return new Product(name, price, stock, promotion); + } + + private void addProductToInventory(Product product) { + Optional<Product> existingProduct = findProductByNameAndPromotion(product.getName(), product.getPromotion()); + if (existingProduct.isEmpty()) { + products.add(product); + return; + } + existingProduct.get().addStock(product.getStock()); + } + + private Optional<Product> findProductByNameAndPromotion(String name, Promotion promotion) { + return products.stream() + .filter(product -> isMatchingProduct(product, name, promotion)) + .findFirst(); + } + + private boolean isMatchingProduct(Product product, String name, Promotion promotion) { + if (!product.getName().equals(name)) { + return false; + } + return isMatchingPromotion(product, promotion); + } + + private boolean isMatchingPromotion(Product product, Promotion promotion) { + if (product.getPromotion() == null && promotion == null) { + return true; + } + if (product.getPromotion() != null) { + return product.getPromotion().equals(promotion); + } + return false; + } + + public Optional<Product> getProductByNameAndPromotion(String productName, boolean hasPromotion) { + return products.stream() + .filter(product -> isMatchingProductByNameAndPromotion(product, productName, hasPromotion)) + .findFirst(); + } + + private boolean isMatchingProductByNameAndPromotion(Product product, String productName, boolean hasPromotion) { + if (!product.getName().equalsIgnoreCase(productName)) { + return false; + } + if (hasPromotion) { + return product.getPromotion() != null; + } + return product.getPromotion() == null; + } + + public void updateInventory(Cart cart) { + validateStock(cart); + reduceStock(cart); + } + + private void validateStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + int totalAvailableStock = getTotalAvailableStock(product); + + if (requiredQuantity > totalAvailableStock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + } + } + + private int getTotalAvailableStock(Product product) { + int availablePromoStock = getAvailablePromoStock(product); + int availableRegularStock = getAvailableRegularStock(product); + return availablePromoStock + availableRegularStock; + } + + private int getAvailablePromoStock(Product product) { + Optional<Product> promoProduct = getProductByNameAndPromotion(product.getName(), true); + if (promoProduct.isPresent()) { + return promoProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private int getAvailableRegularStock(Product product) { + Optional<Product> regularProduct = getProductByNameAndPromotion(product.getName(), false); + if (regularProduct.isPresent()) { + return regularProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private void reduceStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + + int promoQuantity = calculatePromoQuantity(product, requiredQuantity); + int regularQuantity = requiredQuantity - promoQuantity; + + reduceStock(product.getName(), promoQuantity, regularQuantity); + } + } + + private int calculatePromoQuantity(Product product, int requiredQuantity) { + if (product.getPromotion() == null) { + return EMPTY_PROMOTION; + } + if (!product.getPromotion().isValid(DateTimes.now().toLocalDate())) { + return EMPTY_PROMOTION; + } + return Math.min(requiredQuantity, product.getStock()); + } + + private void reduceStock(String productName, int promoQuantity, int regularQuantity) { + reducePromotionStock(productName, promoQuantity); + reduceRegularStock(productName, regularQuantity); + } + + private void reducePromotionStock(String productName, int promoQuantity) { + if (promoQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> promoProduct = getProductByNameAndPromotion(productName, true); + if (promoProduct.isPresent()) { + promoProduct.get().reducePromotionStock(promoQuantity); + } + } + + private void reduceRegularStock(String productName, int regularQuantity) { + if (regularQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> regularProduct = getProductByNameAndPromotion(productName, false); + if (regularProduct.isPresent()) { + regularProduct.get().reduceRegularStock(regularQuantity); + } + } + + public void printProductList(StoreOutput storeOutput) { + storeOutput.printProductList(products); + } +}
Java
ํ”„๋กœ๋ชจ์…˜์˜ ๊ธฐ๊ฐ„์„ ๋ฏธ๋ฆฌ ํŒ๋‹จํ•ด์„œ loadํ•˜์‹œ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ด์ง€๋งŒ ๊ธฐ๊ฐ„์ด ์ง€๋‚ฌ์„ ๋•Œ `์ฝœ๋ผ 1,000์› 10๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ`๊ณผ ๊ฐ™์ด ์ถœ๋ ฅํ•  ๊ฒฝ์šฐ `MD์ถ”์ฒœ์ƒํ’ˆ` ๋ถ€๋ถ„์€ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•˜์…จ์„๊นŒ์š”?
@@ -0,0 +1,64 @@ +package store.io.input.impl; + +import camp.nextstep.edu.missionutils.Console; +import store.common.ConsoleMessages; +import store.common.ErrorMessages; +import store.io.input.StoreInput; + + +public class InputConsole implements StoreInput { + + @Override + public String getPurchaseItemsInput() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.PURCHASE_ITEMS_PROMPT); + return Console.readLine(); + } + + @Override + public boolean askForAdditionalPromo(String itemName, int additionalCount) { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf(ConsoleMessages.ADDITIONAL_PROMO_PROMPT + ConsoleMessages.LINE_SEPARATOR, itemName, + additionalCount); + return getYesNoResponse(); + } + + @Override + public boolean askForFullPricePurchase(String itemName, int shortageCount) { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf(ConsoleMessages.FULL_PRICE_PURCHASE_PROMPT + ConsoleMessages.LINE_SEPARATOR, itemName, + shortageCount); + return getYesNoResponse(); + } + + @Override + public boolean askForMembershipDiscount() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.MEMBERSHIP_DISCOUNT_PROMPT); + return getYesNoResponse(); + } + + @Override + public boolean askForAdditionalPurchase() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.ADDITIONAL_PURCHASE_PROMPT); + return getYesNoResponse(); + } + + private boolean getYesNoResponse() { + while (true) { + try { + String input = Console.readLine(); + if ("Y".equals(input)) { + return true; + } + if ("N".equals(input)) { + return false; + } + throw new IllegalArgumentException(ErrorMessages.INVALID_INPUT_MESSAGE); + } catch (IllegalArgumentException e) { + System.out.println(ErrorMessages.ERROR_MESSAGE + e.getMessage()); + } + } + } +}
Java
์ด 2๊ฐœ์˜ if๋ฌธ์„ ๋ณ„๊ฐœ์˜ ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์—ˆ์œผ๋ฉด ํ•จ์ˆ˜ ๋ผ์ธ์ด ์ข€ ๋” ์ค„์–ด๋“ค ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,12 @@ +package store.common; + +public class ConsoleMessages { + public static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."; + public static final String PRODUCT_LIST_HEADER = "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String PURCHASE_ITEMS_PROMPT = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String ADDITIONAL_PROMO_PROMPT = "ํ˜„์žฌ %s์€(๋Š”) %d๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String FULL_PRICE_PURCHASE_PROMPT = "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String MEMBERSHIP_DISCOUNT_PROMPT = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String ADDITIONAL_PURCHASE_PROMPT = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + public static final String LINE_SEPARATOR = System.lineSeparator(); +}
Java
enum์€ ์„œ๋กœ ๊ด€๋ จ์ด ์žˆ๋Š” ์ƒ์ˆ˜ ์ง‘ํ•ฉ์„ ๋‚˜ํƒ€๋‚ผ ๋•Œ ์‚ฌ์šฉํ•˜๋Š”๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. ํƒ€์ž… ์•ˆ์ •์„ฑ์„ ๊ฐ•์กฐํ•˜๋Š” enum๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ ๋‹จ์ง€ ๋ฌธ์ž์—ด์ด๋‚˜ ์ˆซ์ž ๊ฐ’์— ๋Œ€ํ•œ ์žฌ์‚ฌ์šฉ์„ฑ์˜ ์˜๋ฏธ๋ฅผ ์ „๋‹ฌํ•˜๊ณ  ์‹ถ์—ˆ์–ด์š”. ์‚ฌ์‹ค ์ด๋Ÿฐ ๊ฐ„๋‹จํ•œ ๋ฌธ์ž์—ด ์ถœ๋ ฅ๊นŒ์ง€ ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌํ•ด์•ผํ•˜๋‚˜ ์‹ถ์—ˆ์ง€๋งŒ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์˜ ๋‚ด์šฉ์„ ๋ฌด์‹œํ•  ์ˆœ ์—†์–ด์„œ ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌ ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,90 @@ +package store.controller; + +import java.util.List; +import store.domain.Cart; +import store.domain.Membership; +import store.domain.ParsedItem; +import store.domain.Receipt; +import store.io.input.StoreInput; +import store.io.output.StoreOutput; +import store.service.ConvenienceStoreService; + +public class ConvenienceStoreController { + private final StoreInput storeInput; + private final StoreOutput storeOutput; + private final ConvenienceStoreService convenienceStoreService; + + public ConvenienceStoreController(StoreInput storeInput, StoreOutput storeOutput, + ConvenienceStoreService convenienceStoreService) { + this.storeInput = storeInput; + this.storeOutput = storeOutput; + this.convenienceStoreService = convenienceStoreService; + } + + public void start() { + boolean continueShopping; + try { + do { + executeShoppingCycle(); + continueShopping = getValidAdditionalPurchaseResponse(); + } while (continueShopping); + } finally { + storeOutput.close(); + } + } + + private void executeShoppingCycle() { + convenienceStoreService.printInventoryProductList(storeOutput); + + List<ParsedItem> parsedItems = getValidParsedItems(); + Cart cart = convenienceStoreService.createCart(parsedItems); + + convenienceStoreService.applyPromotionToCartItems(cart, storeInput); + + Membership membership = getValidMembershipResponse(); + + Receipt receipt = convenienceStoreService.createReceipt(cart); + storeOutput.printReceipt(receipt, cart, membership); + + updateInventory(cart); + } + + private List<ParsedItem> getValidParsedItems() { + while (true) { + try { + String input = storeInput.getPurchaseItemsInput(); + return convenienceStoreService.parseItems(input); + } catch (IllegalArgumentException | IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private Membership getValidMembershipResponse() { + while (true) { + try { + return convenienceStoreService.determineMembership(storeInput); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private void updateInventory(Cart cart) { + try { + convenienceStoreService.updateInventory(cart); + } catch (IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + + private boolean getValidAdditionalPurchaseResponse() { + while (true) { + try { + return storeInput.askForAdditionalPurchase(); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } +}
Java
๊ธฐ๋ณธ ์ œ๋„ค๋ฆญ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ์ข€ ๋” ๊ฐ€๋…์„ฑ ์ข‹์€ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š” ! ์ข‹์€ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ด์š” :)
@@ -0,0 +1,90 @@ +package store.controller; + +import java.util.List; +import store.domain.Cart; +import store.domain.Membership; +import store.domain.ParsedItem; +import store.domain.Receipt; +import store.io.input.StoreInput; +import store.io.output.StoreOutput; +import store.service.ConvenienceStoreService; + +public class ConvenienceStoreController { + private final StoreInput storeInput; + private final StoreOutput storeOutput; + private final ConvenienceStoreService convenienceStoreService; + + public ConvenienceStoreController(StoreInput storeInput, StoreOutput storeOutput, + ConvenienceStoreService convenienceStoreService) { + this.storeInput = storeInput; + this.storeOutput = storeOutput; + this.convenienceStoreService = convenienceStoreService; + } + + public void start() { + boolean continueShopping; + try { + do { + executeShoppingCycle(); + continueShopping = getValidAdditionalPurchaseResponse(); + } while (continueShopping); + } finally { + storeOutput.close(); + } + } + + private void executeShoppingCycle() { + convenienceStoreService.printInventoryProductList(storeOutput); + + List<ParsedItem> parsedItems = getValidParsedItems(); + Cart cart = convenienceStoreService.createCart(parsedItems); + + convenienceStoreService.applyPromotionToCartItems(cart, storeInput); + + Membership membership = getValidMembershipResponse(); + + Receipt receipt = convenienceStoreService.createReceipt(cart); + storeOutput.printReceipt(receipt, cart, membership); + + updateInventory(cart); + } + + private List<ParsedItem> getValidParsedItems() { + while (true) { + try { + String input = storeInput.getPurchaseItemsInput(); + return convenienceStoreService.parseItems(input); + } catch (IllegalArgumentException | IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private Membership getValidMembershipResponse() { + while (true) { + try { + return convenienceStoreService.determineMembership(storeInput); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private void updateInventory(Cart cart) { + try { + convenienceStoreService.updateInventory(cart); + } catch (IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + + private boolean getValidAdditionalPurchaseResponse() { + while (true) { + try { + return storeInput.askForAdditionalPurchase(); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } +}
Java
10์ค„ ์ดํ•˜๋ผ๋Š” ๊ธฐ์ค€์ด ๋ช…ํ™•ํ•œ ์˜๋„ ์ „๋‹ฌ๊ณผ ๋ถˆํ•„์š”ํ•œ ๋ณต์žก์„ฑ ๋•Œ๋ฌธ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์š”. ์ฝ๊ธฐ ์‰ฝ๊ฒŒ ๋…ผ๋ฆฌ์  ํ๋ฆ„์„ ์œ ์ง€ํ•œ๋‹ค๋ฉด ์—ฌ๋Ÿฌ ๋ฉ”์„œ๋“œ๋กœ ๋ถ„๋ฆฌํ•œ ์ฝ”๋“œ๋ณด๋‹ค ์ข€ ๋” ์ฝ๊ธฐ ์‰ฝ์ง€ ์•Š์„๊นŒ์š” ? ํ•ด๋‹น ์ฝ”๋“œ๊ฐ€ ์ฝ๊ธฐ ์–ด๋ ค์šฐ์‹œ๋‹ค๋ฉด ์–ด๋–ค ๋ถ€๋ถ„์ด ๋ฌธ์ œ๋ผ๊ณ  ์ƒ๊ฐํ•˜์„ธ์š” ?
@@ -0,0 +1,135 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; + +public class CartItem { + private static final int DEFAULT_FREE_QUANTITY = 0; + private static final int MINIMUM_VALID_QUANTITY = 0; + + private final Product product; + private final int quantity; + + public CartItem(Product product, int quantity) { + this.product = product; + this.quantity = quantity; + } + + public Money calculateTotalPrice() { + return product.calculateTotalPrice(quantity); + } + + public int calculatePromotionDiscount() { + if (!product.isPromotionValid()) { + return 0; + } + Money totalAmount = calculateTotalPrice(); + Money amountWithoutPromotion = getTotalAmountWithoutPromotion(); + return totalAmount.subtract(amountWithoutPromotion).getAmount(); + } + + public int calculateTotalIfNoPromotion() { + if (!product.isPromotionValid()) { + return calculateTotalPrice().getAmount(); + } + return 0; + } + + public Money getTotalAmountWithoutPromotion() { + return product.calculatePrice(getEffectivePaidQuantity()); + } + + public int getEffectivePaidQuantity() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return quantity; + } + return calculateQuotient(promotion); + } + + private int calculateQuotient(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + return quantity - Math.min(quantity / totalRequired, product.getStock() / totalRequired); + } + + public boolean isPromotionValid() { + Promotion promotion = product.getPromotion(); + return isPromotionValid(promotion); + } + + private boolean isPromotionValid(Promotion promotion) { + return promotion != null && promotion.isValid(DateTimes.now().toLocalDate()); + } + + public boolean checkPromotionStock() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return false; + } + return isStockAvailable(promotion); + } + + private boolean isStockAvailable(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int promoAvailableQuantity = (product.getStock() / totalRequired) * totalRequired; + return (quantity - promoAvailableQuantity) > MINIMUM_VALID_QUANTITY; + } + + public int getFreeQuantity() { + Promotion promotion = product.getPromotion(); + if (promotion == null) { + return DEFAULT_FREE_QUANTITY; + } + return promotion.calculateFreeItems(quantity, product.getStock()); + } + + public int calculateRemainingQuantity() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return quantity; + } + return calculateRemainingQuantityForValidPromotion(promotion); + } + + private int calculateRemainingQuantityForValidPromotion(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int promoAvailableQuantity = (product.getStock() / totalRequired) * totalRequired; + return Math.max(MINIMUM_VALID_QUANTITY, quantity - promoAvailableQuantity); + } + + public int calculateAdditionalQuantityNeeded() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return DEFAULT_FREE_QUANTITY; + } + return calculateAdditionalQuantity(promotion); + } + + private int calculateAdditionalQuantity(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int remainder = quantity % totalRequired; + if (remainder == promotion.getBuyQuantity()) { + return totalRequired - remainder; + } + return DEFAULT_FREE_QUANTITY; + } + + public CartItem withUpdatedQuantityForFullPrice(int newQuantity) { + return new CartItem(this.product, newQuantity); + } + + public CartItem withAdditionalQuantity(int additionalQuantity) { + return new CartItem(this.product, this.quantity + additionalQuantity); + } + + public String getProductName() { + return product.getName(); + } + + public Product getProduct() { + return product; + } + + public int getQuantity() { + return quantity; + } +}
Java
์ข‹์€ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ด์š” :)
@@ -0,0 +1,64 @@ +package store.io.input.impl; + +import camp.nextstep.edu.missionutils.Console; +import store.common.ConsoleMessages; +import store.common.ErrorMessages; +import store.io.input.StoreInput; + + +public class InputConsole implements StoreInput { + + @Override + public String getPurchaseItemsInput() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.PURCHASE_ITEMS_PROMPT); + return Console.readLine(); + } + + @Override + public boolean askForAdditionalPromo(String itemName, int additionalCount) { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf(ConsoleMessages.ADDITIONAL_PROMO_PROMPT + ConsoleMessages.LINE_SEPARATOR, itemName, + additionalCount); + return getYesNoResponse(); + } + + @Override + public boolean askForFullPricePurchase(String itemName, int shortageCount) { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf(ConsoleMessages.FULL_PRICE_PURCHASE_PROMPT + ConsoleMessages.LINE_SEPARATOR, itemName, + shortageCount); + return getYesNoResponse(); + } + + @Override + public boolean askForMembershipDiscount() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.MEMBERSHIP_DISCOUNT_PROMPT); + return getYesNoResponse(); + } + + @Override + public boolean askForAdditionalPurchase() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.ADDITIONAL_PURCHASE_PROMPT); + return getYesNoResponse(); + } + + private boolean getYesNoResponse() { + while (true) { + try { + String input = Console.readLine(); + if ("Y".equals(input)) { + return true; + } + if ("N".equals(input)) { + return false; + } + throw new IllegalArgumentException(ErrorMessages.INVALID_INPUT_MESSAGE); + } catch (IllegalArgumentException e) { + System.out.println(ErrorMessages.ERROR_MESSAGE + e.getMessage()); + } + } + } +}
Java
์ข‹์€ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ด์š” :)
@@ -0,0 +1,238 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.common.ErrorMessages; +import store.io.output.StoreOutput; + +public class Inventory { + private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String MD_FILE_DELIMITER = ","; + + private static final int NAME_INDEX = 0; + private static final int BUY_QUANTITY_INDEX = 1; + private static final int FREE_QUANTITY_INDEX = 2; + private static final int START_DATE_INDEX = 3; + private static final int END_DATE_INDEX = 4; + private static final int PRICE_INDEX = 1; + private static final int STOCK_INDEX = 2; + private static final int PROMOTION_NAME_INDEX = 3; + + private static final int DEFAULT_STOCK = 0; + private static final int EMPTY_PROMOTION = 0; + + private final List<Product> products = new ArrayList<>(); + private final Map<String, Promotion> promotions = new HashMap<>(); + + public Inventory() { + loadPromotions(); + loadProducts(); + } + + private void loadPromotions() { + LocalDate currentDate = DateTimes.now().toLocalDate(); + try (BufferedReader reader = new BufferedReader(new FileReader(PROMOTIONS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Promotion promotion = parsePromotion(line); + addPromotionToMap(promotion, currentDate); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PROMOTIONS_FILE); + } + } + + private Promotion parsePromotion(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int buyQuantity = Integer.parseInt(fields[BUY_QUANTITY_INDEX]); + int freeQuantity = Integer.parseInt(fields[FREE_QUANTITY_INDEX]); + LocalDate startDate = LocalDate.parse(fields[START_DATE_INDEX]); + LocalDate endDate = LocalDate.parse(fields[END_DATE_INDEX]); + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } + + private void addPromotionToMap(Promotion promotion, LocalDate currentDate) { + if (!promotion.isValid(currentDate)) { + promotions.put(promotion.getName(), null); + return; + } + promotions.put(promotion.getName(), promotion); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Product product = parseProduct(line); + addProductToInventory(product); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PRODUCTS_FILE); + } + } + + private Product parseProduct(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int price = Integer.parseInt(fields[PRICE_INDEX]); + int stock = Integer.parseInt(fields[STOCK_INDEX]); + + String promotionName = null; + if (fields.length > PROMOTION_NAME_INDEX) { + promotionName = fields[PROMOTION_NAME_INDEX]; + } + + Promotion promotion = promotions.get(promotionName); + return new Product(name, price, stock, promotion); + } + + private void addProductToInventory(Product product) { + Optional<Product> existingProduct = findProductByNameAndPromotion(product.getName(), product.getPromotion()); + if (existingProduct.isEmpty()) { + products.add(product); + return; + } + existingProduct.get().addStock(product.getStock()); + } + + private Optional<Product> findProductByNameAndPromotion(String name, Promotion promotion) { + return products.stream() + .filter(product -> isMatchingProduct(product, name, promotion)) + .findFirst(); + } + + private boolean isMatchingProduct(Product product, String name, Promotion promotion) { + if (!product.getName().equals(name)) { + return false; + } + return isMatchingPromotion(product, promotion); + } + + private boolean isMatchingPromotion(Product product, Promotion promotion) { + if (product.getPromotion() == null && promotion == null) { + return true; + } + if (product.getPromotion() != null) { + return product.getPromotion().equals(promotion); + } + return false; + } + + public Optional<Product> getProductByNameAndPromotion(String productName, boolean hasPromotion) { + return products.stream() + .filter(product -> isMatchingProductByNameAndPromotion(product, productName, hasPromotion)) + .findFirst(); + } + + private boolean isMatchingProductByNameAndPromotion(Product product, String productName, boolean hasPromotion) { + if (!product.getName().equalsIgnoreCase(productName)) { + return false; + } + if (hasPromotion) { + return product.getPromotion() != null; + } + return product.getPromotion() == null; + } + + public void updateInventory(Cart cart) { + validateStock(cart); + reduceStock(cart); + } + + private void validateStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + int totalAvailableStock = getTotalAvailableStock(product); + + if (requiredQuantity > totalAvailableStock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + } + } + + private int getTotalAvailableStock(Product product) { + int availablePromoStock = getAvailablePromoStock(product); + int availableRegularStock = getAvailableRegularStock(product); + return availablePromoStock + availableRegularStock; + } + + private int getAvailablePromoStock(Product product) { + Optional<Product> promoProduct = getProductByNameAndPromotion(product.getName(), true); + if (promoProduct.isPresent()) { + return promoProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private int getAvailableRegularStock(Product product) { + Optional<Product> regularProduct = getProductByNameAndPromotion(product.getName(), false); + if (regularProduct.isPresent()) { + return regularProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private void reduceStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + + int promoQuantity = calculatePromoQuantity(product, requiredQuantity); + int regularQuantity = requiredQuantity - promoQuantity; + + reduceStock(product.getName(), promoQuantity, regularQuantity); + } + } + + private int calculatePromoQuantity(Product product, int requiredQuantity) { + if (product.getPromotion() == null) { + return EMPTY_PROMOTION; + } + if (!product.getPromotion().isValid(DateTimes.now().toLocalDate())) { + return EMPTY_PROMOTION; + } + return Math.min(requiredQuantity, product.getStock()); + } + + private void reduceStock(String productName, int promoQuantity, int regularQuantity) { + reducePromotionStock(productName, promoQuantity); + reduceRegularStock(productName, regularQuantity); + } + + private void reducePromotionStock(String productName, int promoQuantity) { + if (promoQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> promoProduct = getProductByNameAndPromotion(productName, true); + if (promoProduct.isPresent()) { + promoProduct.get().reducePromotionStock(promoQuantity); + } + } + + private void reduceRegularStock(String productName, int regularQuantity) { + if (regularQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> regularProduct = getProductByNameAndPromotion(productName, false); + if (regularProduct.isPresent()) { + regularProduct.get().reduceRegularStock(regularQuantity); + } + } + + public void printProductList(StoreOutput storeOutput) { + storeOutput.printProductList(products); + } +}
Java
addPromotionToMap()์€ Promotion ๊ฐ์ฒด๋ฅผ promotions ๋งต์— ์ถ”๊ฐ€ํ•˜๋Š” ๊ณผ์ • ์ด์—์š”. ํ”„๋กœ๋ชจ์…˜์˜ ์œ ํšจ์„ฑ์„ ๊ฒ€์‚ฌํ•˜๊ณ , ์œ ํšจํ•˜์ง€ ์•Š์€ ํ”„๋กœ๋ชจ์…˜์€ null๋กœ ์ถ”๊ฐ€ํ•˜์—ฌ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ด ์ง€๋‚œ ์ƒํ’ˆ์€ ์ผ๋ฐ˜ ์žฌ๊ณ ์™€ ํ•ฉ์ณ ๊ด€๋ฆฌํ•˜๋„๋ก ํ–ˆ์–ด์š” :)
@@ -0,0 +1,12 @@ +package store.common; + +public class ConsoleMessages { + public static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."; + public static final String PRODUCT_LIST_HEADER = "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String PURCHASE_ITEMS_PROMPT = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String ADDITIONAL_PROMO_PROMPT = "ํ˜„์žฌ %s์€(๋Š”) %d๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String FULL_PRICE_PURCHASE_PROMPT = "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String MEMBERSHIP_DISCOUNT_PROMPT = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String ADDITIONAL_PURCHASE_PROMPT = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + public static final String LINE_SEPARATOR = System.lineSeparator(); +}
Java
์ €๋„ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์—์„œ ์ƒ์ˆ˜ํ™”์— ๋Œ€ํ•ด ์˜ฌ๋ผ์™€์„œ ์ฒ˜์Œ์—๋Š” ๋ชจ๋‘ ์ƒ์ˆ˜ํ™”๋ฅผ ์ง„ํ–‰ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์˜๋ฌธ์ด ๋“ค์–ด ํ•˜๋“œ ์ฝ”๋”ฉ๋œ ๋‚ด์šฉ์ด ์–ด๋–ค ๋‚ด์šฉ์ธ์ง€ ํ•œ๋ฒˆ์— ํŒŒ์•…ํ•˜๊ธฐ ํž˜๋“  ๊ฒฝ์šฐ์—๋งŒ ์ƒ์ˆ˜ํ™”๋ฅผ ํ•˜๋„๋ก ์ €๋งŒ์˜ ๊ธฐ์ค€์„ ์žก์•˜์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,26 @@ +package store.config; + +import store.controller.ConvenienceStoreController; +import store.io.input.StoreInput; +import store.io.input.impl.InputConsole; +import store.io.output.StoreOutput; +import store.io.output.impl.OutputConsole; +import store.service.ConvenienceStoreService; + +public class ConvenienceStoreConfig { + public StoreInput storeInput() { + return new InputConsole(); + } + + public StoreOutput storeOutput() { + return new OutputConsole(); + } + + public ConvenienceStoreService convenienceStoreService() { + return new ConvenienceStoreService(); + } + + public ConvenienceStoreController convenienceStoreController() { + return new ConvenienceStoreController(storeInput(), storeOutput(), convenienceStoreService()); + } +}
Java
์ €๋„ ๋ฐ›์•˜๋˜ ์ง€์ ์ธ๋ฐ ํ˜„์žฌ Config์—์„œ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ์ƒ์„ฑ์„ ํ•˜๋ฉด ๋งค๋ฒˆ input, output,service ๋ชจ๋‘ ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ฒŒ๋ฉ๋‹ˆ๋‹ค! ์ผ๋ถ€๋กœ ์˜๋„ํ•˜์‹ ๊ฑด์ง€๋Š” ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ ์ €๋Š” ์ถ”ํ›„์— ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์œผ๋กœ ๋ฆฌํŒฉํ† ๋งํ•  ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค!ใ…Žใ…Ž