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 ๋ชจ๋ ์๋ก์ด ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ฒ๋ฉ๋๋ค! ์ผ๋ถ๋ก ์๋ํ์ ๊ฑด์ง๋ ๋ชจ๋ฅด๊ฒ ์ง๋ง ์ ๋ ์ถํ์ ์ฑ๊ธํค ํจํด์ผ๋ก ๋ฆฌํฉํ ๋งํ ์๊ฐ์
๋๋ค!ใ
ใ
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.