code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
์ €๋Š” ์ด ๋ฉ”์„œ๋“œ์˜ ๊ธฐ๋Šฅ์ด ํ•ด๋‹น ํด๋ž˜์Šค์— ์žˆ๋Š”๊ฒƒ๋ณด๋‹ค Product์— ์žˆ๋Š”๊ฒŒ ์ ์ ˆํ•œ๊ฑฐ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐ์ด ๋“œ๋Š”๋ฐ ํ•ด๋‹น ํด๋ž˜์Šค์— ๋„ฃ์œผ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
์ฒ˜์Œ๋ณด๋Š” ํ˜•์‹์ธ๋ฐ ์–ด๋–ค ๊ธฐ๋Šฅ์„ ํ•˜๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
order์— ๋„ฃ๋Š” ๋ถ€๋ถ„์ด parserOrder์— ์žˆ์–ด์„œ ์ด ๋ถ€๋ถ„์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ „๋‹ฌํ•ด์ฃผ๊ณ  putToOrders์—์„œ ์ง์ ‘ orders์— ๋„ฃ๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ๋ฉ”์„œ๋“œ ์ด๋ฆ„์— ์ ํ•ฉํ•œ ๊ธฐ๋Šฅ์„ ํ• ๊ฑฐ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์„œ ์ž‘์„ฑํ•ด๋ด…๋‹ˆ๋‹ค.
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
splitํ•˜๋Š” ๋ถ€๋ถ„์˜ regex๋„ ์ƒ์ˆ˜ํ™”ํ•˜๋ฉด ์ข‹์„๊ฑฐ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐ๋“ญ๋‹ˆ๋‹ค
@@ -0,0 +1,120 @@ +package store.domain; + +import static store.util.Constant.MEMBERSHIP_DISCOUNT_LIMIT; +import static store.util.Constant.MEMBERSHIP_DISCOUNT_RATE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +public class Receipt { + + private final Map<Product, Integer> purchaseHistory; + private final Map<Product, Integer> giveAwayHistory; + private int membershipApplicableAmount; + + public Receipt() { + purchaseHistory = new LinkedHashMap<>(); + giveAwayHistory = new LinkedHashMap<>(); + } + + public void addPurchaseHistory(Product product, int quantity) { + purchaseHistory.put(product, quantity); + } + + public void addGiveAwayHistory(Product product, Promotion promotion, int quantity) { + int bundle = promotion.getBuy() + promotion.getGet(); + int giveAwayQuantity = Math.min(quantity, product.getQuantity()) / bundle; + if (giveAwayQuantity != 0) { + giveAwayHistory.put(product, giveAwayQuantity); + } + } + + public void applyMembershipDiscount(Promotions promotions) { + for (Map.Entry<Product, Integer> purchaseInfo : purchaseHistory.entrySet()) { + Product product = purchaseInfo.getKey(); + int quantity = purchaseInfo.getValue(); + if (!hasGiveAway(product.getName())) { + membershipApplicableAmount += product.getPrice() * quantity; + continue; + } + int promotionApplicableQuantity = calculatePromotionApplicableQuantity(product, promotions); + membershipApplicableAmount += product.getPrice() * (quantity - promotionApplicableQuantity); + } + } + + private int calculatePromotionApplicableQuantity(Product product, Promotions promotions) { + int giveAwayQuantity = findGiveAwayQuantity(product.getName()); + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + int bundle = promotion.calculateBundle(); + return bundle * giveAwayQuantity; + } + + private boolean hasGiveAway(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return true; + } + } + return false; + } + + private int findGiveAwayQuantity(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return giveAwayInfo.getValue(); + } + } + return 0; + } + + public int calculateTotalPurchaseAmount() { + int totalPurchaseAmount = 0; + for (Map.Entry<Product, Integer> giveAway : purchaseHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + totalPurchaseAmount += product.getPrice() * quantity; + } + return totalPurchaseAmount; + } + + public int calculateTotalQuantity() { + int totalQuantity = 0; + for (Integer quantity : purchaseHistory.values()) { + totalQuantity += quantity; + } + return totalQuantity; + } + + public int calculatePromotionDiscount() { + int promotionDiscount = 0; + for (Map.Entry<Product, Integer> giveAway : giveAwayHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + promotionDiscount += product.getPrice() * quantity; + } + return promotionDiscount; + } + + public int calculateMembershipDiscount() { + int membershipDiscount = (int) (membershipApplicableAmount * MEMBERSHIP_DISCOUNT_RATE); + return Math.min(MEMBERSHIP_DISCOUNT_LIMIT, membershipDiscount); + } + + public int calculatePayment() { + int totalPurchaseAmount = calculateTotalPurchaseAmount(); + int promotionDiscount = calculatePromotionDiscount(); + int membershipDiscount = calculateMembershipDiscount(); + return totalPurchaseAmount - promotionDiscount - membershipDiscount; + } + + public Map<Product, Integer> getPurchaseHistory() { + return Collections.unmodifiableMap(purchaseHistory); + } + + public Map<Product, Integer> getGiveAwayHistory() { + return Collections.unmodifiableMap(giveAwayHistory); + } +}
Java
inventory์—์„œ ๋น„์Šทํ•œ ์—ญํ• ์„ ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋ณธ๊ฑฐ ๊ฐ™์€๋ฐ ์ž๋ฃŒํ˜• ๋•Œ๋ฌธ์— ์ƒˆ๋กœ ๋งŒ๋“œ์‹ ๊ฑด๊ฐ€์š”..?
@@ -0,0 +1,86 @@ +package store.controller; + +import static store.util.Constant.ANSWER_NO; +import static store.util.InformationMessage.WELCOME_MESSAGE; +import static store.util.Validator.validateAnswer; +import static store.view.InputView.readForAdditionalPurchase; +import static store.view.OutputView.displayReceipt; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import store.service.PaymentService; +import store.domain.Inventory; +import store.domain.Order; +import store.domain.Promotions; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private final Inventory inventory; + private final Promotions promotions; + + public StoreController() { + inventory = prepareInventory(); + promotions = preparePromotions(); + } + + public void run() { + do { + OutputView.printMessage(WELCOME_MESSAGE); + OutputView.printInventory(inventory); + Order order = inputOrder(inventory); + PaymentService paymentService = new PaymentService(inventory, promotions, order); + displayReceipt(paymentService.getReceipt()); + } while (!inputAdditionalPurchase().equals(ANSWER_NO)); + closeConsole(); + } + + Inventory prepareInventory() { + Inventory inventory; + try { + inventory = new Inventory(); + return inventory; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Promotions preparePromotions() { + Promotions promotions; + try { + promotions = new Promotions(); + return promotions; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Order inputOrder(Inventory inventory) { + while (true) { + try { + Order order = new Order(InputView.readOrder()); + inventory.checkOrder(order); + return order; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + String inputAdditionalPurchase() { + while (true) { + try { + String answer = readForAdditionalPurchase(); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + void closeConsole() { + Console.close(); + } +}
Java
private๋กœ ์•ˆํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”? controller์—์„œ๋Š” ์•„๋ฌด๋‚˜ ์ ‘๊ทผํ•˜์ง€ ๋ชปํ•˜๋„๋ก ์ ‘๊ทผ์ œํ•œ์ž๋ฅผ ์„ค์ •ํ•ด ๋†“๋Š”๊ฒŒ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
Inventory์˜ ์—ญํ• ์ด ๋„ˆ๋ฌด ๋งŽ์•„๋ณด์—ฌ์š”. find๋‚˜ add ๊ฐ™์€ CRUD ๊ฐœ๋…์€ 3-way-architecture๋ฅผ ์ด์šฉํ•ด๋ณด์‹œ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
์ €๋„ ๋„๋ฉ”์ธ์—์„œ ๊ฒ€์ฆํ•˜๋Š” ๊ฒŒ ์žˆ๋Š”๊ฑธ ์ข‹์•„ํ•˜๋Š” ํŽธ์ธ๋ฐ ํ•ด๋‹น ์ œ๊ฐ€ ์ƒ๊ฐํ•˜๋Š” ์ด๋ฒˆ ํŽธ์˜์ ์—์„œ๋Š” orderCount๋ฅผ ๋ฏธ๋ฆฌ parseํ•˜๋Š” ๊ฒŒ ๋” ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,158 @@ +package store.service; + +import static store.util.Constant.ANSWER_NO; +import static store.util.Constant.ANSWER_YES; +import static store.util.Validator.validateAnswer; +import static store.view.InputView.readForAdditionalItem; +import static store.view.InputView.readForMembershipDiscount; +import static store.view.InputView.readForOutOfStock; + +import java.util.LinkedHashMap; +import java.util.Map; +import store.domain.Inventory; +import store.domain.Order; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Promotions; +import store.domain.Receipt; +import store.view.OutputView; + +public class PaymentService { + + private final Map<String, Integer> shoppingCart; + private final Receipt receipt; + + public PaymentService(Inventory inventory, Promotions promotions, Order order) { + shoppingCart = new LinkedHashMap<>(); + receipt = new Receipt(); + checkPromotionProduct(inventory, promotions, order); + updatePurchaseHistory(inventory); + updateGiveAwayHistory(inventory, promotions, order); + updateInventory(inventory, promotions); + checkMembershipDiscount(promotions); + } + + private void checkMembershipDiscount(Promotions promotions) { + String answer = inputForMembershipDiscount(); + if (answer.equals(ANSWER_YES)) { + receipt.applyMembershipDiscount(promotions); + } + } + + private void updateInventory(Inventory inventory, Promotions promotions) { + shoppingCart.forEach((productName, quantity) -> { + Product product = inventory.findProductWithPromotion(productName); + if (product != null && promotions.isPromotionApplicable(product)) { + inventory.reducePromotionStock(productName, quantity); + return; + } + inventory.reduceNotPromotionStock(productName, quantity); + }); + } + + private void updatePurchaseHistory(Inventory inventory) { + shoppingCart.forEach((productName, quantity) -> { + Product product = inventory.findProductWithPromotion(productName); + if (product == null) { + product = inventory.findProductWithoutPromotion(productName); + } + receipt.addPurchaseHistory(product, quantity); + }); + } + + private void updateGiveAwayHistory(Inventory inventory, Promotions promotions, Order order) { + shoppingCart.forEach((productName, quantity) -> { + Product product = inventory.findProductWithPromotion(productName); + if (product != null && promotions.isPromotionApplicable(product)) { + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + receipt.addGiveAwayHistory(product, promotion, quantity); + } + }); + } + + private void checkPromotionProduct(Inventory inventory, Promotions promotions, Order order) { + Map<String, Integer> orders = order.getOrders(); + orders.forEach((productName, quantity) -> { + shoppingCart.put(productName, quantity); + Product product = inventory.findProductWithPromotion(productName); + if (product != null && promotions.isPromotionApplicable(product)) { + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + checkBenefitOrOutOfStock(product, promotion, Map.entry(productName, quantity)); + } + }); + } + + private void checkBenefitOrOutOfStock(Product product, Promotion promotion, Map.Entry<String, Integer> order) { + String productName = order.getKey(); + int quantity = order.getValue(); + if (canApplyPromotionBenefit(product, promotion, Map.entry(productName, quantity))) { + if (inputForAdditionalItem(productName).equals(ANSWER_YES)) { + shoppingCart.put(productName, quantity + 1); + } + return; + } + checkOutOfStock(product, promotion, Map.entry(productName, quantity)); + } + + private boolean canApplyPromotionBenefit(Product product, Promotion promotion, Map.Entry<String, Integer> order) { + int bundle = promotion.calculateBundle(); + int quantity = order.getValue(); + if (quantity < product.getQuantity()) { + return quantity % bundle == bundle - 1; + } + return false; + } + + private void checkOutOfStock(Product product, Promotion promotion, Map.Entry<String, Integer> order) { + int bundle = promotion.calculateBundle(); + int shareOfOrder = order.getValue() / bundle; + int shareOfProduct = product.getQuantity() / bundle; + int shortageQuantity = order.getValue() - (Math.min(shareOfOrder, shareOfProduct) * bundle); + if (shortageQuantity != 0) { + String answer = inputForOutOfStock(order.getKey(), shortageQuantity); + if (answer.equals(ANSWER_NO)) { + shoppingCart.put(order.getKey(), order.getValue() - shortageQuantity); + } + } + } + + private String inputForOutOfStock(String productName, int shortageQuantity) { + while (true) { + try { + String answer = readForOutOfStock(productName, shortageQuantity); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + private String inputForAdditionalItem(String productName) { + while (true) { + try { + String answer = readForAdditionalItem(productName); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + private String inputForMembershipDiscount() { + while (true) { + try { + String answer = readForMembershipDiscount(); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + public Receipt getReceipt() { + return receipt; + } +}
Java
์ €๋Š” service์—์„œ input, output์„ ํ•˜๋Š” ๊ฑด ์—ญํ• ์— ์•ˆ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. controller๊ฐ€ ์‚ฌ์šฉ์ž์—๊ฒŒ ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ์„ ๋‹ด๋‹นํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ service์—์„œ ํ•˜๋Š” ์—ญํ• ์ด ์•„๋‹ˆ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,86 @@ +package store.controller; + +import static store.util.Constant.ANSWER_NO; +import static store.util.InformationMessage.WELCOME_MESSAGE; +import static store.util.Validator.validateAnswer; +import static store.view.InputView.readForAdditionalPurchase; +import static store.view.OutputView.displayReceipt; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import store.service.PaymentService; +import store.domain.Inventory; +import store.domain.Order; +import store.domain.Promotions; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private final Inventory inventory; + private final Promotions promotions; + + public StoreController() { + inventory = prepareInventory(); + promotions = preparePromotions(); + } + + public void run() { + do { + OutputView.printMessage(WELCOME_MESSAGE); + OutputView.printInventory(inventory); + Order order = inputOrder(inventory); + PaymentService paymentService = new PaymentService(inventory, promotions, order); + displayReceipt(paymentService.getReceipt()); + } while (!inputAdditionalPurchase().equals(ANSWER_NO)); + closeConsole(); + } + + Inventory prepareInventory() { + Inventory inventory; + try { + inventory = new Inventory(); + return inventory; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Promotions preparePromotions() { + Promotions promotions; + try { + promotions = new Promotions(); + return promotions; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Order inputOrder(Inventory inventory) { + while (true) { + try { + Order order = new Order(InputView.readOrder()); + inventory.checkOrder(order); + return order; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + String inputAdditionalPurchase() { + while (true) { + try { + String answer = readForAdditionalPurchase(); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + void closeConsole() { + Console.close(); + } +}
Java
ํ•ด๋‹น ์ฝ”๋“œ๋Š” InputView์—์„œ ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์–ด์„œ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ˆ˜ํ–‰ํ–ˆ์œผ๋ฉด ๋” ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์–ด์š”! import camp.nextstep.edu.missionutils.Console; ๋™์ผํ•œ import ๊ตฌ๋ฌธ์ด InputView์—๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด์—์š”!
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
์ผ๊ธ‰ ์ปฌ๋ ‰์…˜ ๋ฐฉ์‹์„ ์ด์šฉํ•˜์—ฌ Inventory ํด๋ž˜์Šค์—์„œ ์ƒํ’ˆ์˜ ์ˆ˜๋Ÿ‰ ๊ฐ์†Œ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์‹  ๊ฒƒ ๊ฐ™์•„์š”! ๊ฐ์ฒด๋ฅผ ๊ฐ์ฒด๋‹ต๊ฒŒ ํ™œ์šฉํ•˜๋ ค๋Š” ์ ‘๊ทผ์ด ๋‹๋ณด์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ํ•œ ๊ฐ€์ง€ ์•„์‰ฌ์šด ์ ์€ ํ˜„์žฌ ์ˆ˜๋Ÿ‰๋งŒํผ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด reduceQuantity๋ฅผ ์—ฌ๋Ÿฌ ๋ฒˆ ํ˜ธ์ถœํ•˜๊ณ  ์žˆ๋‹ค๋Š” ์ ์ž…๋‹ˆ๋‹ค. ์ด ๋Œ€์‹ , ํ•ด๋‹น ์ƒํ’ˆ(Product)์— ์ฐจ๊ฐํ•  ์ˆ˜๋Ÿ‰์„ ํ•œ ๋ฒˆ์— ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ฐœ์„ ํ•˜๋ฉด ๋ถˆํ•„์š”ํ•œ ๋ฐ˜๋ณต๋ฌธ์„ ์ค„์ด๊ณ  ์„ฑ๋Šฅ๋„ ๊ฐœ์„ ๋  ๊ฒƒ ๊ฐ™์•„์š”! ``` private void reduceProduct(Product product, int quantity) { product.reduceQuantity(quantity); } ``` ์ด๋ ‡๊ฒŒ ๊ฐœ์„ ํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•ด์ง€๊ณ , Product ํด๋ž˜์Šค์—์„œ๋„ ์ˆ˜๋Ÿ‰์„ ํ•œ ๋ฒˆ์— ์ค„์ผ ์ˆ˜ ์žˆ์–ด ๋ช…ํ™•ํ•œ ์ฑ…์ž„ ๋ถ„๋ฆฌ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
๋ถˆ๋ณ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์œ„ํ•œ ๋ฉ”์„œ๋“œ๋กœ ์•Œ๊ณ ์žˆ์–ด์š”! ์™ธ๋ถ€์—์„œ ์ˆ˜์ •์„ ๋ฐฉ์ง€ํ•˜๊ณ  ์•ˆ์ •์„ฑ์„ ๋ณด์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค! ์ €๋„ ์ผ๊ธ‰์ปฌ๋ ‰์…˜ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์„œ ํ˜น์‹œ๋‚˜ ๋„์›€์ด ๋˜์…จ์œผ๋ฉด ํ•˜๋Š” ๋งˆ์Œ์— ๋‹ต๋ณ€ ๋‹ฌ์•„๋ด…๋‹ˆ๋‹ค!
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
์‰ผํ‘œ(,)์™€ ๊ฐ™์€ ์˜๋ฏธ ์žˆ๋Š” ๊ธฐํ˜ธ๋ฅผ ์ƒ์ˆ˜๋กœ์จ ๋ถ„๋ฆฌ๋ฅผ ํ•˜์‹œ๋ฉด ์œ ์ง€ ๋ณด์ˆ˜ ๊ด€์ ์—์„œ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์–ด์š”!
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
split์„ ์‚ฌ์šฉํ•˜์…จ์ง€๋งŒ List๋ฅผ ์ด์šฉํ•˜์‹œ๊ธฐ ์œ„ํ—ค List.of๋ฅผ ์ด์šฉํ•˜์‹  ์ ์ด ๋‹๋ณด์ด๋„ค์š”!
@@ -0,0 +1,120 @@ +package store.domain; + +import static store.util.Constant.MEMBERSHIP_DISCOUNT_LIMIT; +import static store.util.Constant.MEMBERSHIP_DISCOUNT_RATE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +public class Receipt { + + private final Map<Product, Integer> purchaseHistory; + private final Map<Product, Integer> giveAwayHistory; + private int membershipApplicableAmount; + + public Receipt() { + purchaseHistory = new LinkedHashMap<>(); + giveAwayHistory = new LinkedHashMap<>(); + } + + public void addPurchaseHistory(Product product, int quantity) { + purchaseHistory.put(product, quantity); + } + + public void addGiveAwayHistory(Product product, Promotion promotion, int quantity) { + int bundle = promotion.getBuy() + promotion.getGet(); + int giveAwayQuantity = Math.min(quantity, product.getQuantity()) / bundle; + if (giveAwayQuantity != 0) { + giveAwayHistory.put(product, giveAwayQuantity); + } + } + + public void applyMembershipDiscount(Promotions promotions) { + for (Map.Entry<Product, Integer> purchaseInfo : purchaseHistory.entrySet()) { + Product product = purchaseInfo.getKey(); + int quantity = purchaseInfo.getValue(); + if (!hasGiveAway(product.getName())) { + membershipApplicableAmount += product.getPrice() * quantity; + continue; + } + int promotionApplicableQuantity = calculatePromotionApplicableQuantity(product, promotions); + membershipApplicableAmount += product.getPrice() * (quantity - promotionApplicableQuantity); + } + } + + private int calculatePromotionApplicableQuantity(Product product, Promotions promotions) { + int giveAwayQuantity = findGiveAwayQuantity(product.getName()); + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + int bundle = promotion.calculateBundle(); + return bundle * giveAwayQuantity; + } + + private boolean hasGiveAway(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return true; + } + } + return false; + } + + private int findGiveAwayQuantity(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return giveAwayInfo.getValue(); + } + } + return 0; + } + + public int calculateTotalPurchaseAmount() { + int totalPurchaseAmount = 0; + for (Map.Entry<Product, Integer> giveAway : purchaseHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + totalPurchaseAmount += product.getPrice() * quantity; + } + return totalPurchaseAmount; + } + + public int calculateTotalQuantity() { + int totalQuantity = 0; + for (Integer quantity : purchaseHistory.values()) { + totalQuantity += quantity; + } + return totalQuantity; + } + + public int calculatePromotionDiscount() { + int promotionDiscount = 0; + for (Map.Entry<Product, Integer> giveAway : giveAwayHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + promotionDiscount += product.getPrice() * quantity; + } + return promotionDiscount; + } + + public int calculateMembershipDiscount() { + int membershipDiscount = (int) (membershipApplicableAmount * MEMBERSHIP_DISCOUNT_RATE); + return Math.min(MEMBERSHIP_DISCOUNT_LIMIT, membershipDiscount); + } + + public int calculatePayment() { + int totalPurchaseAmount = calculateTotalPurchaseAmount(); + int promotionDiscount = calculatePromotionDiscount(); + int membershipDiscount = calculateMembershipDiscount(); + return totalPurchaseAmount - promotionDiscount - membershipDiscount; + } + + public Map<Product, Integer> getPurchaseHistory() { + return Collections.unmodifiableMap(purchaseHistory); + } + + public Map<Product, Integer> getGiveAwayHistory() { + return Collections.unmodifiableMap(giveAwayHistory); + } +}
Java
``` int promotionApplicableQuantity = calculatePromotionApplicableQuantity(product, promotions); membershipApplicableAmount += product.getPrice() * (quantity - promotionApplicableQuantity); ``` ํ•ด๋‹น ์ฝ”๋“œ๋ฅผ ๋ฉ”์„œ๋“œ ๋ถ„๋ฆฌํ•˜์…”์„œ ํ•œ ๋ผ์ธ์œผ๋กœ ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ–ˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,81 @@ +package store.view; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.ERROR_TAG; +import static store.util.Constant.RECEIPT_AMOUNT_INFO_TITLE; +import static store.util.Constant.RECEIPT_GIVEAWAY_TITLE; +import static store.util.Constant.RECEIPT_TITLE; +import static store.util.InformationMessage.INTRODUCE_PRODUCT_MESSAGE; +import static store.util.MessageTemplate.PRODUCT_INFO; +import static store.util.MessageTemplate.PRODUCT_INFO_ZERO_QUANTITY; +import static store.util.MessageTemplate.RECEIPT_DISCOUNT; +import static store.util.MessageTemplate.RECEIPT_GIVEAWAY_HISTORY; +import static store.util.MessageTemplate.RECEIPT_HEADER; +import static store.util.MessageTemplate.RECEIPT_PAYMENT; +import static store.util.MessageTemplate.RECEIPT_PURCHASE_HISTORY; +import static store.util.MessageTemplate.RECEIPT_TOTAL_PURCHASE_AMOUNT; + +import java.util.List; +import java.util.Map; +import store.domain.Inventory; +import store.domain.Product; +import store.domain.Receipt; + +public class OutputView extends View { + + private OutputView() {} + + public static void printInventory(Inventory inventory) { + printMessage(INTRODUCE_PRODUCT_MESSAGE); + printNewLine(); + List<Product> products = inventory.getProducts(); + for (Product product : products) { + printProductInfo(product); + } + } + + public static void printProductInfo(Product product) { + if (!product.isZeroQuantity()) { + printMessage(PRODUCT_INFO.format(product.getName(), product.getPrice(), product.getQuantity(), + product.getPromotionName())); + return; + } + printMessage( + PRODUCT_INFO_ZERO_QUANTITY.format(product.getName(), product.getPrice(), product.getPromotionName())); + } + + public static void displayReceipt(Receipt receipt) { + printMessage(RECEIPT_TITLE); + printMessage(RECEIPT_HEADER.format("์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก")); + displayPurchaseHistory(receipt); + displayGiveAwayHistory(receipt); + displayAmountInfo(receipt); + } + + private static void displayAmountInfo(Receipt receipt) { + printMessage(RECEIPT_AMOUNT_INFO_TITLE); + printMessage(RECEIPT_TOTAL_PURCHASE_AMOUNT.format("์ด๊ตฌ๋งค์•ก", receipt.calculateTotalQuantity(), + receipt.calculateTotalPurchaseAmount())); + printMessage(RECEIPT_DISCOUNT.format("ํ–‰์‚ฌํ• ์ธ", BLANK, receipt.calculatePromotionDiscount())); + printMessage(RECEIPT_DISCOUNT.format("๋ฉค๋ฒ„์‹ญํ• ์ธ", BLANK, receipt.calculateMembershipDiscount())); + printMessage(RECEIPT_PAYMENT.format("๋‚ด์‹ค๋ˆ", BLANK, receipt.calculatePayment())); + } + + private static void displayGiveAwayHistory(Receipt receipt) { + printMessage(RECEIPT_GIVEAWAY_TITLE); + receipt.getGiveAwayHistory().forEach((product, quantity) -> { + printMessage(RECEIPT_GIVEAWAY_HISTORY.format(product.getName(), quantity)); + }); + } + + private static void displayPurchaseHistory(Receipt receipt) { + Map<Product, Integer> purchaseHistory = receipt.getPurchaseHistory(); + purchaseHistory.forEach((product, quantity) -> { + printMessage(RECEIPT_PURCHASE_HISTORY.format(product.getName(), quantity, product.getPrice() * quantity)); + }); + } + + public static void printError(String errorMessage) { + printMessage(ERROR_TAG + errorMessage); + } +}
Java
์•ˆ๋…•ํ•˜์„ธ์š”! ํ˜น์‹œ ์•„๋ž˜์™€ ๊ฐ™์ด ํฌ๋งท์„ ์„ค์ •ํ•˜์…จ์„ ๋•Œ, ๋„์–ด์“ฐ๊ธฐ ๋•Œ๋ฌธ์— ์ถœ๋ ฅ์ด ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ •๋ ฌ์ด ๋˜์…จ๋‚˜์š”?? 4์ฃผ ์ฐจ ์ง„ํ–‰ํ•˜๋ฉด์„œ ์˜์ˆ˜์ฆ ์ถœ๋ ฅ ๋ถ€๋ถ„์„ ๋ณด๊ธฐ ์ข‹๊ฒŒ ์ •๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์š”๊ตฌ์‚ฌํ•ญ์ด์—ˆ์–ด์„œ ๋งŽ์ด ์ฐพ์•„๋ดค์Šต๋‹ˆ๋‹ค! ๊ทธ ๊ณผ์ •์—์„œ ์•Œ๊ฒŒ ๋œ ์ ์€, ํ•œ๊ตญ์–ด๋Š” 2๊ธ€์ž๋กœ ์ทจ๊ธ‰๋˜์ง€๋งŒ, ๋„์–ด์“ฐ๊ธฐ์™€ ์˜์–ด๋Š” 1๊ธ€์ž๋กœ ์ทจ๊ธ‰๋œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋„์–ด์“ฐ๊ธฐ๋ฅผ ํ•œ๊ธ€์ฒ˜๋Ÿผ 2๊ธ€์ž ์—ญํ• ์„ ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์„๊นŒ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€, \u3000 (์œ ๋‹ˆ์ฝ”๋“œ ๊ณต๋ฐฑ)์„ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค! ์˜ˆ๋ฅผ ๋“ค์–ด, ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค: `String name = String.format("%-14s", "์ด๊ตฌ๋งค์•ก").replace(" ", "\u3000");` ์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•œ๊ธ€์ฒ˜๋Ÿผ ๋„์–ด์“ฐ๊ธฐ๋ฅผ 2๊ธ€์ž ์ทจ๊ธ‰ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์ •๋ ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค! ๐Ÿ˜Š
@@ -0,0 +1,86 @@ +package store.controller; + +import static store.util.Constant.ANSWER_NO; +import static store.util.InformationMessage.WELCOME_MESSAGE; +import static store.util.Validator.validateAnswer; +import static store.view.InputView.readForAdditionalPurchase; +import static store.view.OutputView.displayReceipt; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import store.service.PaymentService; +import store.domain.Inventory; +import store.domain.Order; +import store.domain.Promotions; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private final Inventory inventory; + private final Promotions promotions; + + public StoreController() { + inventory = prepareInventory(); + promotions = preparePromotions(); + } + + public void run() { + do { + OutputView.printMessage(WELCOME_MESSAGE); + OutputView.printInventory(inventory); + Order order = inputOrder(inventory); + PaymentService paymentService = new PaymentService(inventory, promotions, order); + displayReceipt(paymentService.getReceipt()); + } while (!inputAdditionalPurchase().equals(ANSWER_NO)); + closeConsole(); + } + + Inventory prepareInventory() { + Inventory inventory; + try { + inventory = new Inventory(); + return inventory; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Promotions preparePromotions() { + Promotions promotions; + try { + promotions = new Promotions(); + return promotions; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Order inputOrder(Inventory inventory) { + while (true) { + try { + Order order = new Order(InputView.readOrder()); + inventory.checkOrder(order); + return order; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + String inputAdditionalPurchase() { + while (true) { + try { + String answer = readForAdditionalPurchase(); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + void closeConsole() { + Console.close(); + } +}
Java
์ผ๋ฐ˜์ ์œผ๋กœ do-while๋ณด๋‹ค๋Š” while๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์กฐ๊ฑด์„ ๋จผ์ € ํ™•์ธํ•˜๋Š” ๊ฒƒ์ด ๋” ๋ช…ํ™•ํ•˜๊ณ  ๊ฐ€๋…์„ฑ๋„ ํ–ฅ์ƒ๋œ๋‹ค๊ณ  ์•Œ๊ณ  ์žˆ์–ด์š”! while ๋ฌธ์„ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, ์ฝ”๋“œ ํ๋ฆ„์ด ๋ช…ํ™•ํ•ด์ ธ์„œ ์œ ์ง€๋ณด์ˆ˜ํ•  ๋•Œ ๋” ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๐Ÿ˜Š
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
ํ˜•๋ณ€ํ™˜์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹์€ ์ž ์žฌ์ ์ธ ์˜ค๋ฅ˜๋ฅผ ์œ ๋ฐœํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๊ฐ€๋Šฅํ•œ ํ•œ ๊ตฌ์ฒด์ ์ธ ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜์—ฌ ์•ˆ์ „ํ•˜๊ณ  ๊ฐ€๋…์„ฑ์ด ์ข‹์€ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์˜ˆ๋ฅผ ๋“ค์–ด, `List<Object>` ํƒ€์ž…์„ `List<String>, List<ProductInfo>` ๋ฐ”๊พธ์–ด ๊ตฌ์ฒด์ ์ธ ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•˜๋ฉด ํ˜•๋ณ€ํ™˜์„ ํ”ผํ•  ์ˆ˜ ์žˆ์–ด์š” ```java private Product createProduct(List<String> productInfo) { String name = productInfo.get(0); int price = Integer.parseInt(productInfo.get(1)); int quantity = Integer.parseInt(productInfo.get(2)); String promotion = productInfo.get(3); return new Product(name, price, quantity, promotion); } ```
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
๋ฐ˜๋ณต๋˜๋Š” ์ฝ”๋“œ๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜Š
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
์ด ๋ถ€๋ถ„์€ ์ŠคํŠธ๋ฆผ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”! ```java public boolean hasProduct(String name) { return products.stream() .anyMatch(product -> name.equals(product.getName())); } ```
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
์Œ,, ํ˜น์‹œ ์ด๋Ÿฌ๋ฉด [์ฝœ๋ผ[-3]] ์ด๋ ‡๊ฒŒ ์ž‘์„ฑ๋ผ๋„ ํ†ต๊ณผ๋  ๊ฑฐ ๊ฐ™์€๋ฐ ์•„๋‹Œ๊ฐ€์š” ??
@@ -0,0 +1,40 @@ +package store.domain; + +import java.time.LocalDateTime; + +public class Promotion { + + private final String name; + private final int buy; + private final int get; + private final LocalDateTime startDate; + private final LocalDateTime endDate; + + public Promotion(String name, int buy, int get, LocalDateTime startDate, LocalDateTime endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public boolean canApply(LocalDateTime now) { + return now.isAfter(startDate) && now.isBefore(endDate); + } + + public int calculateBundle() { + return buy + get; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } +}
Java
startDate์™€ endDate ๋Š” DateRange ๊ฐ™์€ ํด๋ž˜์Šค๋ฅผ ํ†ตํ•ด ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋‚˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,40 @@ +package store.domain; + +import java.time.LocalDateTime; + +public class Promotion { + + private final String name; + private final int buy; + private final int get; + private final LocalDateTime startDate; + private final LocalDateTime endDate; + + public Promotion(String name, int buy, int get, LocalDateTime startDate, LocalDateTime endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public boolean canApply(LocalDateTime now) { + return now.isAfter(startDate) && now.isBefore(endDate); + } + + public int calculateBundle() { + return buy + get; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } +}
Java
์ €๋„ ์‹ค์ˆ˜ํ•œ ๋ถ€๋ถ„์ธ๋ฐ, ์ด๋Ÿฌ๋ฉด ํ”„๋กœ๋ชจ์…˜ ์‹œ์ž‘์ผ, ์ข…๋ฃŒ์ผ์ด๋ฉด false ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋”๋ผ๊ตฌ์š” ใ…œใ…œ
@@ -0,0 +1,81 @@ +package store.view; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.ERROR_TAG; +import static store.util.Constant.RECEIPT_AMOUNT_INFO_TITLE; +import static store.util.Constant.RECEIPT_GIVEAWAY_TITLE; +import static store.util.Constant.RECEIPT_TITLE; +import static store.util.InformationMessage.INTRODUCE_PRODUCT_MESSAGE; +import static store.util.MessageTemplate.PRODUCT_INFO; +import static store.util.MessageTemplate.PRODUCT_INFO_ZERO_QUANTITY; +import static store.util.MessageTemplate.RECEIPT_DISCOUNT; +import static store.util.MessageTemplate.RECEIPT_GIVEAWAY_HISTORY; +import static store.util.MessageTemplate.RECEIPT_HEADER; +import static store.util.MessageTemplate.RECEIPT_PAYMENT; +import static store.util.MessageTemplate.RECEIPT_PURCHASE_HISTORY; +import static store.util.MessageTemplate.RECEIPT_TOTAL_PURCHASE_AMOUNT; + +import java.util.List; +import java.util.Map; +import store.domain.Inventory; +import store.domain.Product; +import store.domain.Receipt; + +public class OutputView extends View { + + private OutputView() {} + + public static void printInventory(Inventory inventory) { + printMessage(INTRODUCE_PRODUCT_MESSAGE); + printNewLine(); + List<Product> products = inventory.getProducts(); + for (Product product : products) { + printProductInfo(product); + } + } + + public static void printProductInfo(Product product) { + if (!product.isZeroQuantity()) { + printMessage(PRODUCT_INFO.format(product.getName(), product.getPrice(), product.getQuantity(), + product.getPromotionName())); + return; + } + printMessage( + PRODUCT_INFO_ZERO_QUANTITY.format(product.getName(), product.getPrice(), product.getPromotionName())); + } + + public static void displayReceipt(Receipt receipt) { + printMessage(RECEIPT_TITLE); + printMessage(RECEIPT_HEADER.format("์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก")); + displayPurchaseHistory(receipt); + displayGiveAwayHistory(receipt); + displayAmountInfo(receipt); + } + + private static void displayAmountInfo(Receipt receipt) { + printMessage(RECEIPT_AMOUNT_INFO_TITLE); + printMessage(RECEIPT_TOTAL_PURCHASE_AMOUNT.format("์ด๊ตฌ๋งค์•ก", receipt.calculateTotalQuantity(), + receipt.calculateTotalPurchaseAmount())); + printMessage(RECEIPT_DISCOUNT.format("ํ–‰์‚ฌํ• ์ธ", BLANK, receipt.calculatePromotionDiscount())); + printMessage(RECEIPT_DISCOUNT.format("๋ฉค๋ฒ„์‹ญํ• ์ธ", BLANK, receipt.calculateMembershipDiscount())); + printMessage(RECEIPT_PAYMENT.format("๋‚ด์‹ค๋ˆ", BLANK, receipt.calculatePayment())); + } + + private static void displayGiveAwayHistory(Receipt receipt) { + printMessage(RECEIPT_GIVEAWAY_TITLE); + receipt.getGiveAwayHistory().forEach((product, quantity) -> { + printMessage(RECEIPT_GIVEAWAY_HISTORY.format(product.getName(), quantity)); + }); + } + + private static void displayPurchaseHistory(Receipt receipt) { + Map<Product, Integer> purchaseHistory = receipt.getPurchaseHistory(); + purchaseHistory.forEach((product, quantity) -> { + printMessage(RECEIPT_PURCHASE_HISTORY.format(product.getName(), quantity, product.getPrice() * quantity)); + }); + } + + public static void printError(String errorMessage) { + printMessage(ERROR_TAG + errorMessage); + } +}
Java
์ด๋Ÿฌํ•œ ์ƒํ’ˆ๋ช…, ์ˆ˜๋Ÿ‰, ๊ธˆ์•ก, ์ด๊ตฌ๋งค์•ก, ํ–‰์‚ฌํ• ์ธ, ๋ฉค๋ฒ„์‹ญํ• ์ธ ๋“ฑ ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌํ•˜๋ฉด ๋” ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
close๊นŒ์ง€ ์ƒ๊ฐ๋ชปํ–ˆ๋Š”๋ฐ ๊ผผ๊ผผํ•˜์‹ ๋ฐ์š”!
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
์—ฌ๊ธฐ์„œ ์ผ๊ธ‰์ปฌ๋ ‰์…˜์„ ์‚ฌ์šฉํ•˜์‹  ๊ฑฐ๋ผ๋ฉด, static์ด ์•„๋‹ˆ๋ผ final์ด ๋” ์ ์ ˆํ•ด ๋ณด์ด๋Š”๋ฐ static์„ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
์ด ๋ถ€๋ถ„์€ ์™ธ๋ถ€ ํด๋ž˜์Šค์—์„œ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ์•„๋‹Œ checkProductInventory์—์„œ๋งŒ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์—, private์œผ๋กœ ๋‹ซ์•„๋‘ฌ๋„ ๋  ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,33 @@ +public class Calculator { + public double calculate(String expression) { + String[] tokens = expression.split(" "); + double currentResult = Double.parseDouble(tokens[0]); + + for (int i = 1; i < tokens.length; i += 2) { + String operator = tokens[i]; + double number = Double.parseDouble(tokens[i + 1]); + + switch (operator) { + case "+": + currentResult += number; + break; + case "-": + currentResult -= number; + break; + case "*": + currentResult *= number; + break; + case "/": + if (number == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + currentResult /= number; + break; + default: + System.out.println("์ง€์›ํ•˜์ง€ ์•Š๋Š” ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค: " + operator); + return 0; + } + } + return currentResult; + } +}
Java
Enum์„ ์‚ฌ์šฉํ•ด์„œ switch๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด๋ด…์‹œ๋‹ค
@@ -0,0 +1,33 @@ +public class Calculator { + public double calculate(String expression) { + String[] tokens = expression.split(" "); + double currentResult = Double.parseDouble(tokens[0]); + + for (int i = 1; i < tokens.length; i += 2) { + String operator = tokens[i]; + double number = Double.parseDouble(tokens[i + 1]); + + switch (operator) { + case "+": + currentResult += number; + break; + case "-": + currentResult -= number; + break; + case "*": + currentResult *= number; + break; + case "/": + if (number == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + currentResult /= number; + break; + default: + System.out.println("์ง€์›ํ•˜์ง€ ์•Š๋Š” ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค: " + operator); + return 0; + } + } + return currentResult; + } +}
Java
Calculator ํด๋ž˜์Šค์˜ ์ฑ…์ž„์€ ๋ฌด์—‡์ธ๊ฐ€์š”. ํ•œ ํด๋ž˜์Šค์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ฑ…์ž„์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. SCP์— ๋Œ€ํ•ด์„œ ๊ณต๋ถ€ํ•ด๋ณด๊ณ  ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”
@@ -0,0 +1,34 @@ +public class Validator { + public boolean isValid(String expression) { + String[] tokens = expression.split(" "); + + if (tokens.length % 2 == 0) { + return false; + } + + if (!isNumeric(tokens[0])) { + return false; + } + + for (int i = 1; i < tokens.length; i += 2) { + if (!isOperator(tokens[i]) || !isNumeric(tokens[i + 1])) { + return false; + } + } + + return true; + } + + private boolean isNumeric(String str) { + try { + Double.parseDouble(str); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + private boolean isOperator(String str) { + return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/"); + } +}
Java
ํ•œ ๋ฉ”์†Œ๋“œ๊ฐ€ ๋งŽ์€ ์—ญํ• ์„ ํ•ด์ฃผ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฐ๊ฐ์˜ if๋ฌธ์„ ์—ฌ๋Ÿฌ ๋ฉ”์†Œ๋“œ๋กœ ๋‚˜๋ˆ„์–ด๋ณด์„ธ์š”.
@@ -1,5 +1,22 @@ +import java.util.Scanner; + public class Main { public static void main(String[] args) { - System.out.println("1 + 1 = 2"); + Scanner scanner = new Scanner(System.in); + System.out.println("๊ณ„์‚ฐํ•  ์ˆ˜์‹์„ ์ž…๋ ฅํ•˜์„ธ์š” (์˜ˆ: 30 + 20 / 2 * 4):"); + String expression = scanner.nextLine(); + + Validator validator = new Validator(); + if (validator.isValid(expression)) { + Calculator calculator = new Calculator(); + try { + double result = calculator.calculate(expression); + System.out.println("๊ฒฐ๊ณผ: " + result); + } catch (ArithmeticException e) { + System.out.println("๊ณ„์‚ฐ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: " + e.getMessage()); + } + } else { + System.out.println("์ž˜๋ชป๋œ ์ˆ˜์‹ ํ˜•์‹์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } } }
Java
Main ํด๋ž˜์Šค์— ๋„ˆ๋ฌด ๋งŽ์€ ์ฑ…์ž„์ด ์žˆ์Šต๋‹ˆ๋‹ค. SCP์— ๋Œ€ํ•ด์„œ ๊ณต๋ถ€ ํ•ด๋ณด๊ณ  ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š” * ์ฝ˜์†”์— ํ”„๋ฆฐํŠธํ•ด์ฃผ๋Š” ๊ฒƒ๋„ ํ•˜๋‚˜์˜ ์ฑ…์ž„์œผ๋กœ ๋ด…๋‹ˆ๋‹ค
@@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; @Slf4j @RestController @@ -26,12 +27,24 @@ public class OrderController { private final OrderService orderService; private final BasketService basketService; + + /* + (C) OrderController๊ฐ€ ๊ด€์‹ฌ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ฃผ๋ฌธ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด์ง€ ํŠน์ • ์„œ๋น„์Šค(SQS, SSE)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + MessageService / OrderService / StoreService ๋“ฑ์œผ๋กœ Service๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ์„œ ๊ทธ ์•ˆ์—์„œ SsqService, SseService ๋ฐ converter๋ฅผ ์กฐํ•ฉํ•˜์—ฌ + ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๊ด€์‹ฌ์‚ฌ์˜ ๋ถ„๋ฆฌ๊ฐ€ ๋” ์ ์ ˆํ•˜๊ฒŒ ์ด๋ฃจ์–ด ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ private final SqsService sqsService; private final SseService sseService; private final SendingMessageConverter sendingMessageConverter; - private final ReceivingMessageConverter receivingMessageConverter; + private final ReceivingMessageConverter receivingMessageConverter; // (C) ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์˜์กด์„ฑ์€ ์ง€์›Œ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. - public OrderController(OrderService orderService, BasketService basketService, SqsService sqsService, SseService sseService, SendingMessageConverter sendingMessageConverter, ReceivingMessageConverter receivingMessageConverter) { + /* (C) ์—ฌ๊ธฐ๋„ lombok์˜ RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. */ + public OrderController(OrderService orderService, + BasketService basketService, + SqsService sqsService, + SseService sseService, + SendingMessageConverter sendingMessageConverter, + ReceivingMessageConverter receivingMessageConverter) { this.orderService = orderService; this.basketService = basketService; this.sqsService = sqsService; @@ -43,21 +56,32 @@ public OrderController(OrderService orderService, BasketService basketService, S @GetMapping @ResponseStatus(HttpStatus.OK) public List<OrderPartResponseDto> showOrderList(@RequestAttribute("cognitoUsername") String customerId) { - List<Order> orderList = orderService.getOrderList(customerId).orElseGet(ArrayList::new); - List<OrderPartResponseDto> orderPartInfoList = new ArrayList<>(); - orderList.forEach(order -> { - orderPartInfoList.add(new OrderPartResponseDto(order)); - }); - return orderPartInfoList; + + /* + (C) StreamAPI๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด ๋ณด์ž…๋‹ˆ๋‹ค. + + getOrderList๋Š” Optional์ด ์•„๋‹Œ List<Order> ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค + */ + return orderService.getOrderList(customerId) + .orElseGet(ArrayList::new) + .stream() + .map(OrderPartResponseDto::new) + .collect(Collectors.toList()); } @PostMapping @ResponseStatus(HttpStatus.CREATED) + /* + (C) controller์—์„œ ํ•˜๋Š” ์ผ์ด ๊ฝค ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค๋กœ ๋กœ์ง์„ ๋นผ๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. + */ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, HttpServletResponse response) throws IOException { + /* + 1. (Q) ์—ฌ๊ธฐ๋Š” customerId๊ฐ€ ์™œ basketId๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‚˜์š”? + 2. (C) createOrder๋กœ order๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค๋ฉด, orderId๋ณด๋‹ค๋Š” order ์ž์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์‚ฌ์šฉ์„ฑ ์ธก๋ฉด์—์„œ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ String orderId = orderService.createOrder(customerId, customerId); Optional<Order> orderOptional = orderService.getOrder(orderId); - if(orderOptional.isEmpty()){ + if (orderOptional.isEmpty()) { throw new RuntimeException("Can't create order"); } Order order = orderOptional.get(); @@ -69,9 +93,10 @@ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, @GetMapping("/{orderId}") @ResponseStatus(HttpStatus.OK) public SseEmitter showOrderInfo(@RequestAttribute("cognitoUsername") String customerId, - @PathVariable String orderId){ + @PathVariable String orderId) { SseEmitter sseEmitter = sseService.connect(customerId); sseService.showOrder(customerId, orderId); return sseEmitter; } + } \ No newline at end of file
Java
(C) ๋ถˆํ•„์š”ํ•œ IOException์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -11,6 +11,7 @@ import java.io.IOException; +// (Q) Custom deserializer๋ฅผ ๊ตฌํ˜„ํ•œ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”? Jackson ๋“ฑ์˜ serializer๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์–ด๋ ค์šด ๋ถ€๋ถ„์ด ์žˆ๋‚˜์š”? public class StoreDeserializer extends StdDeserializer { public StoreDeserializer(){
Java
> ๋„ค ์‚ฌ์‹ค Menu ๋ฐ์ดํ„ฐ์™€๋Š” ๋‹ค๋ฅด๊ฒŒ Store ๋ฐ์ดํ„ฐ๋Š” Point๋ผ๋Š” spring์—์„œ ์ œ๊ณตํ•˜๋Š” ๊ฐ์ฒด๋ฅผ property๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ objectMapper์˜ readValue()๋กœ๋Š” Store.class๋ฅผ ๋ฐ”๋กœ ์—ญ์ง๋ ฌํ™”์‹œํ‚ค์ง€ ๋ชปํ•˜๋Š”๋ฐ ๊ทธ๊ฑด ๋ฐ”๋กœ Point๋ฅผ objectMapper๊ฐ€ ํ•ด์„ํ•˜์ง€ ๋ชปํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋”๋ผ๊ณ ์š”. JSONObject.get()์„ ์‚ฌ์šฉํ•ด์„œ ํ•˜๋‚˜ํ•˜๋‚˜ ๊นŒ์„œ ์—ญ์ง๋ ฌํ™”ํ•ด๋„ ๋์ง€๋งŒ, convertStoreData() ๋ฉ”์„œ๋“œ๊ฐ€ ๊ธธ์–ด์ง€๋Š” ๊ฒŒ ๋ณด๊ธฐ ์‹ซ์–ด์„œ Custom deserializer๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ•œ๋ฐฉ์— ์ฒ˜๋ฆฌ๋˜๊ฒŒ๋” ๋ณด์ด๋„๋ก(?) ํ–ˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์‹ค Deserializer๋ฅผ ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ•˜๋Š”์ง€ ์•„์ง ๊ฐ์„ ์ž˜ ๋ชป ์žก์•˜์Šต๋‹ˆ๋‹ค. ์–ด๋–ป๊ฒŒ ํ•˜๋Š”๊ฒŒ ์ข‹์„๊นŒ์š” point ํƒ€์ž…์˜ ๊ฐ์ฒด ๋˜ํ•œ spring boot default serializer(jackson)๋กœ๋„ ์ถฉ๋ถ„ํžˆ serialize/deserialize ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ณ€์ˆ˜๋ช…์„ ๋™์ผํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•ด๋ณด์…จ์„๊นŒ์š”?
@@ -5,27 +5,32 @@ import org.springframework.web.bind.annotation.*; import java.util.ArrayList; +import java.util.Arrays; import java.util.EnumSet; import java.util.List; +import java.util.stream.Collectors; @RestController -@RequestMapping("/customer") +@RequestMapping("/customer") // (R) HomeController์—์„œ url prefix๊ฐ€ customer๋กœ ๋˜์–ด์žˆ๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ ์ด์ƒํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. public class HomeController { @GetMapping @ResponseStatus(HttpStatus.OK) - public String home(){ + public String home() { return "Customer server is activated successfully"; - } + } // (Q) ์–ด๋–ค ์šฉ๋„์˜ ๋ฉ”์„œ๋“œ์ธ๊ฐ€์š”? @GetMapping("/main") @ResponseStatus(HttpStatus.OK) - public List<String> foods() { - List<String> foodKindList = new ArrayList<>(); - for (FoodKind foodKind : EnumSet.allOf(FoodKind.class)){ - foodKindList.add(foodKind.toString()); - } - return foodKindList; + public List<FoodKind> foods() { + /* + (C) ์—ฌ๊ธฐ๋„ Stream API๋ฅผ ์ž˜ ์‚ฌ์šฉํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + ๋‹จ์ˆœํžˆ ์Œ์‹ ์ข…๋ฅ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด๋ผ๋ฉด, ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•ด๋ณด์„ธ์š”. + (enum type์„ return ํ•˜๋”๋ผ๋„ string์œผ๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ๋Š”๋ฐ, ํ•œ๋ฒˆ ํ™•์ธํ•ด์ฃผ์„ธ์š”~!) + + + API์—์„œ set์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋ฌด์ž‘์œ„ ์ˆœ์„œ๋กœ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ์ˆœ์„œ๊ฐ€ ๋ฌด๊ด€ํ•œ ๊ฒฝ์šฐ์—๋งŒ set์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ + return Arrays.stream(FoodKind.values()).toList(); } }
Java
>HomeController์˜ home()์€ ํŠน๋ณ„ํ•œ ์ด์œ  ์—†์ด ์ดˆ๊ธฐ์— ์„œ๋ฒ„๊ฐ€ ์ž˜ ๋Œ์•„๊ฐ€๋Š”์ง€ ํ…Œ์ŠคํŠธ ํ•˜๋ ค๊ณ  ๋„ฃ์–ด๋†“์€ ํ…Œ์ŠคํŠธ ์šฉ๋„์˜ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค. Customer, Restaurant, Rider ์„ธ๊ฐ€์ง€ ์„œ๋ฒ„๋ฅผ ๋„์šฐ๋‹ค๋ณด๋‹ˆ White Error ํŽ˜์ด์ง€๋กœ๋Š” ํ—ท๊ฐˆ๋ ค์„œ ์ž„์‹œ๋กœ ์ž‘์„ฑํ–ˆ๋˜ ์ฝ”๋“œ์ธ๋ฐ, ํ…Œ์ŠคํŠธ ์šฉ๋„๊ธฐ ๋•Œ๋ฌธ์— ์—†์–ด๋„ ๋ฌธ์ œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ํ•ด๋‹น ์ฝ”๋“œ์—๋Š” ์ฃผ์„์„ ๋„ฃ์–ด์•ผ ํ–ˆ์—ˆ๋„ค์š”. > customer, restaurant, rider ์„œ๋ฒ„ ๋ชจ๋‘ home controller๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ, ์‚ฌ์‹ค ์ฃผ ์šฉ๋„๋Š” ์„œ๋ฒ„๊ฐ€ ๋Œ์•„๊ฐ€๋Š”์ง€ ๋ณด๋ ค๊ณ  ๋งŒ๋“ค์–ด๋‘” ๊ฒƒ์ž…๋‹ˆ๋‹ค. url prefix๋„ ์ปจํŠธ๋กค๋Ÿฌ๋ช…๊ณผ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ๊ฒŒ ๊ทธ๊ฒƒ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ํ…Œ์ŠคํŠธ ์šฉ๋„๋กœ ์ž‘์„ฑํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ด์—์š”. ํ•ด๋‹น ํด๋ž˜์Šค๋Š” ์ง€์šฐ๋Š” ๊ฒŒ ๋‚˜์„๊นŒ์š”? ํ”ํžˆ ์ด๋Ÿฌํ•œ ์šฉ๋„์˜ controller๋ฅผ health check controller๋ผ๊ณ  ์ง€์นญํ•ฉ๋‹ˆ๋‹ค. ์šด์˜ ํ™˜๊ฒฝ์—์„œ ์„œ๋ฒ„๊ฐ€ ๋™์ž‘ํ•˜๋Š”์ง€ ์ฃผ๊ธฐ์ ์œผ๋กœ ํ•ด์ฃผ์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๋„ค์ด๋ฐ๋งŒ health-check ์˜๋ฏธ๊ฐ€ ๋“œ๋Ÿฌ๋‚˜๊ฒŒ ํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; @Slf4j @RestController @@ -26,12 +27,24 @@ public class OrderController { private final OrderService orderService; private final BasketService basketService; + + /* + (C) OrderController๊ฐ€ ๊ด€์‹ฌ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ฃผ๋ฌธ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด์ง€ ํŠน์ • ์„œ๋น„์Šค(SQS, SSE)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + MessageService / OrderService / StoreService ๋“ฑ์œผ๋กœ Service๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ์„œ ๊ทธ ์•ˆ์—์„œ SsqService, SseService ๋ฐ converter๋ฅผ ์กฐํ•ฉํ•˜์—ฌ + ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๊ด€์‹ฌ์‚ฌ์˜ ๋ถ„๋ฆฌ๊ฐ€ ๋” ์ ์ ˆํ•˜๊ฒŒ ์ด๋ฃจ์–ด ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ private final SqsService sqsService; private final SseService sseService; private final SendingMessageConverter sendingMessageConverter; - private final ReceivingMessageConverter receivingMessageConverter; + private final ReceivingMessageConverter receivingMessageConverter; // (C) ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์˜์กด์„ฑ์€ ์ง€์›Œ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. - public OrderController(OrderService orderService, BasketService basketService, SqsService sqsService, SseService sseService, SendingMessageConverter sendingMessageConverter, ReceivingMessageConverter receivingMessageConverter) { + /* (C) ์—ฌ๊ธฐ๋„ lombok์˜ RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. */ + public OrderController(OrderService orderService, + BasketService basketService, + SqsService sqsService, + SseService sseService, + SendingMessageConverter sendingMessageConverter, + ReceivingMessageConverter receivingMessageConverter) { this.orderService = orderService; this.basketService = basketService; this.sqsService = sqsService; @@ -43,21 +56,32 @@ public OrderController(OrderService orderService, BasketService basketService, S @GetMapping @ResponseStatus(HttpStatus.OK) public List<OrderPartResponseDto> showOrderList(@RequestAttribute("cognitoUsername") String customerId) { - List<Order> orderList = orderService.getOrderList(customerId).orElseGet(ArrayList::new); - List<OrderPartResponseDto> orderPartInfoList = new ArrayList<>(); - orderList.forEach(order -> { - orderPartInfoList.add(new OrderPartResponseDto(order)); - }); - return orderPartInfoList; + + /* + (C) StreamAPI๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด ๋ณด์ž…๋‹ˆ๋‹ค. + + getOrderList๋Š” Optional์ด ์•„๋‹Œ List<Order> ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค + */ + return orderService.getOrderList(customerId) + .orElseGet(ArrayList::new) + .stream() + .map(OrderPartResponseDto::new) + .collect(Collectors.toList()); } @PostMapping @ResponseStatus(HttpStatus.CREATED) + /* + (C) controller์—์„œ ํ•˜๋Š” ์ผ์ด ๊ฝค ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค๋กœ ๋กœ์ง์„ ๋นผ๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. + */ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, HttpServletResponse response) throws IOException { + /* + 1. (Q) ์—ฌ๊ธฐ๋Š” customerId๊ฐ€ ์™œ basketId๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‚˜์š”? + 2. (C) createOrder๋กœ order๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค๋ฉด, orderId๋ณด๋‹ค๋Š” order ์ž์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์‚ฌ์šฉ์„ฑ ์ธก๋ฉด์—์„œ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ String orderId = orderService.createOrder(customerId, customerId); Optional<Order> orderOptional = orderService.getOrder(orderId); - if(orderOptional.isEmpty()){ + if (orderOptional.isEmpty()) { throw new RuntimeException("Can't create order"); } Order order = orderOptional.get(); @@ -69,9 +93,10 @@ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, @GetMapping("/{orderId}") @ResponseStatus(HttpStatus.OK) public SseEmitter showOrderInfo(@RequestAttribute("cognitoUsername") String customerId, - @PathVariable String orderId){ + @PathVariable String orderId) { SseEmitter sseEmitter = sseService.connect(customerId); sseService.showOrder(customerId, orderId); return sseEmitter; } + } \ No newline at end of file
Java
> Customer๋‹น Basket์€ ํ•˜๋‚˜๋งŒ ๊ฐ€์ง„๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ CustomerId๋ฅผ ๋ฐ”๋กœ BasketId๋กœ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ฌผ๋ก  ๋™์ผํ•œ ๊ฐ’์„ id๋กœ ์‚ฌ์šฉํ•˜์‹œ๋Š” ๊ฒƒ๋„ ๊ธฐ๋Šฅ ๋™์ž‘์— ๋ฌธ์ œ๊ฐ€ ์—†๊ฒ ์ง€๋งŒ, basketId์— customerId๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์ผ๋‹จ ์ฝ”๋“œ์˜ ์˜๋„ ํŒŒ์•…์ด ์–ด๋ ต๊ณ , ์ดํ›„ ๋ถ€์—ฌ๋˜๋Š” id๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฒ€์ƒ‰ํ• ํ…๋ฐ ๊ทธ ๋•Œ๋„ ์‹ค์ˆ˜๋ฅผ ์œ ๋ฐœํ•  ์—ฌ์ง€๊ฐ€ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ฝ”๋“œ ์ˆ˜์ค€์—์„œ ์‹ค์ˆ˜๋ฅผ ์˜ˆ๋ฐฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ถ€๋ถ„์ด ์žˆ๋‹ค๋ฉด ํ•ญ์ƒ ๋ฐฉ์–ดํ•˜๋„๋ก ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; @Slf4j @RestController @@ -26,12 +27,24 @@ public class OrderController { private final OrderService orderService; private final BasketService basketService; + + /* + (C) OrderController๊ฐ€ ๊ด€์‹ฌ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ฃผ๋ฌธ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด์ง€ ํŠน์ • ์„œ๋น„์Šค(SQS, SSE)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + MessageService / OrderService / StoreService ๋“ฑ์œผ๋กœ Service๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ์„œ ๊ทธ ์•ˆ์—์„œ SsqService, SseService ๋ฐ converter๋ฅผ ์กฐํ•ฉํ•˜์—ฌ + ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๊ด€์‹ฌ์‚ฌ์˜ ๋ถ„๋ฆฌ๊ฐ€ ๋” ์ ์ ˆํ•˜๊ฒŒ ์ด๋ฃจ์–ด ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ private final SqsService sqsService; private final SseService sseService; private final SendingMessageConverter sendingMessageConverter; - private final ReceivingMessageConverter receivingMessageConverter; + private final ReceivingMessageConverter receivingMessageConverter; // (C) ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์˜์กด์„ฑ์€ ์ง€์›Œ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. - public OrderController(OrderService orderService, BasketService basketService, SqsService sqsService, SseService sseService, SendingMessageConverter sendingMessageConverter, ReceivingMessageConverter receivingMessageConverter) { + /* (C) ์—ฌ๊ธฐ๋„ lombok์˜ RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. */ + public OrderController(OrderService orderService, + BasketService basketService, + SqsService sqsService, + SseService sseService, + SendingMessageConverter sendingMessageConverter, + ReceivingMessageConverter receivingMessageConverter) { this.orderService = orderService; this.basketService = basketService; this.sqsService = sqsService; @@ -43,21 +56,32 @@ public OrderController(OrderService orderService, BasketService basketService, S @GetMapping @ResponseStatus(HttpStatus.OK) public List<OrderPartResponseDto> showOrderList(@RequestAttribute("cognitoUsername") String customerId) { - List<Order> orderList = orderService.getOrderList(customerId).orElseGet(ArrayList::new); - List<OrderPartResponseDto> orderPartInfoList = new ArrayList<>(); - orderList.forEach(order -> { - orderPartInfoList.add(new OrderPartResponseDto(order)); - }); - return orderPartInfoList; + + /* + (C) StreamAPI๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด ๋ณด์ž…๋‹ˆ๋‹ค. + + getOrderList๋Š” Optional์ด ์•„๋‹Œ List<Order> ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค + */ + return orderService.getOrderList(customerId) + .orElseGet(ArrayList::new) + .stream() + .map(OrderPartResponseDto::new) + .collect(Collectors.toList()); } @PostMapping @ResponseStatus(HttpStatus.CREATED) + /* + (C) controller์—์„œ ํ•˜๋Š” ์ผ์ด ๊ฝค ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค๋กœ ๋กœ์ง์„ ๋นผ๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. + */ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, HttpServletResponse response) throws IOException { + /* + 1. (Q) ์—ฌ๊ธฐ๋Š” customerId๊ฐ€ ์™œ basketId๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‚˜์š”? + 2. (C) createOrder๋กœ order๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค๋ฉด, orderId๋ณด๋‹ค๋Š” order ์ž์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์‚ฌ์šฉ์„ฑ ์ธก๋ฉด์—์„œ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ String orderId = orderService.createOrder(customerId, customerId); Optional<Order> orderOptional = orderService.getOrder(orderId); - if(orderOptional.isEmpty()){ + if (orderOptional.isEmpty()) { throw new RuntimeException("Can't create order"); } Order order = orderOptional.get(); @@ -69,9 +93,10 @@ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, @GetMapping("/{orderId}") @ResponseStatus(HttpStatus.OK) public SseEmitter showOrderInfo(@RequestAttribute("cognitoUsername") String customerId, - @PathVariable String orderId){ + @PathVariable String orderId) { SseEmitter sseEmitter = sseService.connect(customerId); sseService.showOrder(customerId, orderId); return sseEmitter; } + } \ No newline at end of file
Java
> Repository์—์„œ ์Šต๊ด€์ ์œผ๋กœ create์ดํ›„ id๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋กœ์ง์„ ์‚ฌ์šฉํ•˜๋‹ค๋ณด๋‹ˆ ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ์ƒ๊ฐํ•ด๋ณด๋‹ˆ order ์ž์ฒด๋ฅผ ๊ฐ€์ ธ์˜ค๋ฉด getOrder()๋„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๋˜๋‹ˆ ์ฟผ๋ฆฌ ํ•œ ๋ฒˆ์„ ์ ˆ์•ฝํ•˜๊ฒ ๊ตฐ์š”. ์ง€์ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๋ง์”€ํ•ด์ฃผ์‹  ๋ถ€๋ถ„๋„ order ๊ฐ์ฒด๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์˜ ์žฅ์ ์œผ๋กœ ๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ ์ œ๊ฐ€ ๋ฆฌ๋ทฐ๋“œ๋ฆฐ ๊ด€์ ์€ ์กฐ๊ธˆ ๋‹ค๋ฅธ ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค. string ํƒ€์ž…์€ ๋ฒ”์šฉ์ ์ธ primitive ํƒ€์ž…์ด๊ธฐ ๋•Œ๋ฌธ์—, ํด๋ž˜์Šค ์ž์ฒด๋กœ์จ๋Š” ํฐ ์˜๋ฏธ๋ฅผ ๊ฐ–์ง€ ์•Š์Šต๋‹ˆ๋‹ค. (๋‹จ์ง€ string์˜ ์—ญํ• ์„ ํ•˜๋Š” ๊ธฐ๋Šฅ๋“ค์„ ์ œ๊ณตํ•  ๋ฟ์ด๊ฒ ์ฃ ) ํ•˜์ง€๋งŒ order ํƒ€์ž… ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด order๋งŒ์ด ๊ฐ–๊ณ  ์žˆ๋Š” ํด๋ž˜์Šค ์ž์ฒด์˜ ์˜๋ฏธ, ๊ทธ ํด๋ž˜์Šค๊ฐ€ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋Šฅ๋“ค๊ณผ ๋ถ€๊ฐ€ ๋กœ์ง ๋“ฑ์„ ์ฝ”๋“œ์—์„œ ํ‘œํ˜„๋ ฅ์žˆ๊ฒŒ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (๊ฐœ์ธ์ ์œผ๋กœ) ์ €๋Š” ๊ทธ๋Ÿฌํ•œ ์ด์œ ๋กœ ์ตœ๋Œ€ํ•œ primitive type์„ ์„œ๋น„์Šค ์ฝ”๋“œ๋‚˜ ์ปจํŠธ๋กค๋Ÿฌ ์ฝ”๋“œ์—์„œ๋Š” ์ž˜ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ด€๋ จํ•ด์„œ [๋””๋ฏธํ„ฐ ๋ฒ•์น™](https://prohannah.tistory.com/204)์— ๊ด€ํ•ด์„œ๋„ ์•Œ์•„๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -11,6 +11,7 @@ import java.io.IOException; +// (Q) Custom deserializer๋ฅผ ๊ตฌํ˜„ํ•œ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”? Jackson ๋“ฑ์˜ serializer๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์–ด๋ ค์šด ๋ถ€๋ถ„์ด ์žˆ๋‚˜์š”? public class StoreDeserializer extends StdDeserializer { public StoreDeserializer(){
Java
๋„ค ๋™์ผํ•œ ๋ณ€์ˆ˜๋ช…์œผ๋กœ ์ฒ˜๋ฆฌํ–ˆ์ง€๋งŒ, custom deserializer๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. _Cannot construct instance of `org.springframework.data.geo.Point` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)_ Point๋ผ๋Š” ๊ฐ์ฒด๋ฅผ objectMapper๊ฐ€ ๋ชจ๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ๋ฐœ์ƒํ•œ ์ผ์ด๋ผ๊ณ  ํ•˜๋”๊ตฐ์š”. ์•„๋ž˜๋Š” chat GPT๋ฅผ ํ†ตํ•ด ์–ป์€ ๋‹ต๋ณ€์ž…๋‹ˆ๋‹ค. https://chat.openai.com/share/fe6258ed-93d6-446b-a39b-6b9c9d1ac0b1 ๋‹ค๋งŒ ์ œ๊ฐ€ ํ–ˆ๋˜ ๊ฒƒ์ฒ˜๋Ÿผ StoreSqsDto์˜ ๋ชจ๋“  property๋ฅผ custom deserialize ํ•  ํ•„์š” ์—†์ด Point๋งŒ custom์œผ๋กœ ๋“ฑ๋กํ•˜๋ฉด ๋˜๊ฒ ๊ตฐ์š”.
@@ -11,6 +11,7 @@ import java.io.IOException; +// (Q) Custom deserializer๋ฅผ ๊ตฌํ˜„ํ•œ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”? Jackson ๋“ฑ์˜ serializer๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์–ด๋ ค์šด ๋ถ€๋ถ„์ด ์žˆ๋‚˜์š”? public class StoreDeserializer extends StdDeserializer { public StoreDeserializer(){
Java
@millwheel ์•„ Point๊ฐ€ ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๊ฐ€ ์—†๊ตฐ์š”. ์ œ๊ฐ€ ์•Œ๊ณ ์žˆ๋Š” ์ผ๋ฐ˜์ ์ธ serializer์˜ deserialize ๋ฐฉ์‹์€, ๋จผ์ € ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  setter๋ฅผ ํ†ตํ•ด ๊ฐ์ฒด ํ•„๋“œ๋ฅผ settingํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๊ฐ€ ์—†๋‹ค๋ณด๋‹ˆ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ณผ์ •์—์„œ ์—๋Ÿฌ๊ฐ€ ๋‚˜๋Š” ๊ฒƒ ๊ฐ™๋„ค์š”~ ์‚ฌ์‹ค point ํด๋ž˜์Šค์™€ ๊ด€๋ จํ•ด์„œ๋„ ๋ฆฌ๋ทฐ ๋“œ๋ฆฌ๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ, ์ดํ›„ ๊ด€๋ จ ๋ฆฌ๋ทฐ์—์„œ ๋” ์–˜๊ธฐํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค~
@@ -19,11 +19,16 @@ @RestController @Slf4j +/* + (C) foodKind๋Š” QueryParam์œผ๋กœ ๋ฐ›๋Š” ๊ฒƒ์ด ๋” restful ํ•ด๋ณด์ž…๋‹ˆ๋‹ค. + ๋˜ํ•œ showStoreInfo์—์„œ๋Š” foodKind๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—, ๊ฐœ๋ณ„ ๋ฉ”์„œ๋“œ์—์„œ ๋งตํ•‘ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„ ๋ณด์ž…๋‹ˆ๋‹ค. +*/ @RequestMapping("/customer/{foodKind}/store") public class StoreController { private final MemberService memberService; private final StoreService storeService; + /* (C) lombok์˜ @RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. */ public StoreController(MemberService memberService, StoreService storeService) { this.memberService = memberService; this.storeService = storeService; @@ -33,11 +38,31 @@ public StoreController(MemberService memberService, StoreService storeService) { @ResponseStatus(HttpStatus.OK) public List<StorePartResponseDto> showStoreList(@RequestAttribute("cognitoUsername") String customerId, @PathVariable FoodKind foodKind, - HttpServletResponse response) throws IOException { + HttpServletResponse response /* ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” param์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. */) throws IOException { + /* + 1. (A) MemberService์— ์™œ coordinates๋ฅผ ํš๋“ํ•˜๋Š” ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ๋Š” ๊ฒƒ์ธ์ง€ ๋ฐ”๋กœ ์ดํ•ดํ•˜๊ธฐ๋Š” ์‚ด์ง ์–ด๋ ค์› ์Šต๋‹ˆ๋‹ค. + coordinates๋ณด๋‹ค๋Š” location์ด๋ผ๋Š” ๋‹จ์–ด๊ฐ€ ๋‹ค๋ฅธ ํด๋ž˜์Šค๋“ค์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๋„๋ฉ”์ธ ์šฉ์–ด(Customer.location)์™€๋„ ํ†ต์ผ๋˜๊ณ  ๋” ์ดํ•ดํ•˜๊ธฐ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + + 2. (C) Optional ํƒ€์ž…์€ ํš๋“ํ•˜์ž๋งˆ์ž ํ•„์š”ํ•œ ํ›„์ฒ˜๋ฆฌ(orElseThrow, isEmpty ๋“ฑ)๋ฅผ ํ•ด์ฃผ์–ด์„œ + ์•„๋ž˜์˜ isEmpty์™€ ๊ฐ™์€ optional check ๋กœ์ง์ด ์—ฌ๋Ÿฌ ์ฝ”๋“œ์— ํผ์ง€์ง€ ์•Š๋„๋ก ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. + MemberService.getCoordinates ๋‚ด์—์„œ orElseThrow ๋“ฑ์œผ๋กœ optional check & un-wrapํ•˜๊ณ , Point ํƒ€์ž…์œผ๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”. + */ Optional<Point> coordinates = memberService.getCoordinates(customerId); if(coordinates.isEmpty()){ + /* + (R) NPE๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ non-nullableํ•œ ๊ณณ์— null ๊ฐ’์ด ์„ธํŒ…๋˜์—ˆ์„ ๋•Œ ๋ฐœ์ƒํ•˜๋Š” exception์ž…๋‹ˆ๋‹ค. + Empty coordinates์— NPE๋ฅผ ๋˜์ง€๋ฉด ์˜๋ฏธ์˜ ํ˜ผ๋™์ด ์žˆ์„ ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. + ์ž๋ฐ” ์ŠคํŽ™์ธ NPE๋ณด๋‹ค๋Š”, ํ”„๋กœ์ ํŠธ์—์„œ empty์˜ ์˜๋ฏธ๋ฅผ ๊ฐ–๋Š” exception์„ customํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. + empty๋„ ์–ด๋–ค ๋Œ€์ƒ์ด emptyํ•œ์ง€๋ฅผ ์„ธ๋ถ„ํ™”ํ•˜์—ฌ ๋‚˜ํƒ€๋‚ด๋ฉด ๋” ์œ ์˜๋ฏธํ•œ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ throw new NullPointerException("Customer has no location information."); } + + /* + (A) ์ฑ… clean code์—์„œ๋Š” collection์˜ ์ž๋ฃŒํ˜•์„ ๋ณ€์ˆ˜๋ช…์— ๋ถ™์ด์ง€ ๋ง ๊ฒƒ์„ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค. + list -> set ๋“ฑ์œผ๋กœ collection ํƒ€์ž…์ด ๋ณ€๊ฒฝ๋˜๋ฉด storePartSet์œผ๋กœ ๋ณ€๊ฒฝํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ๋•Œ๋ฌธ์—, + storeParts, stores์™€ ๊ฐ™์€ ๋ณต์ˆ˜ํ˜•์œผ๋กœ ๋‚˜ํƒ€๋‚ด๊ธฐ๋ฅผ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค. + */ List<StorePartResponseDto> storePartList = new ArrayList<>(); List<Store> storeList = storeService.getStoreListNearCustomer(coordinates.get(), foodKind); storeList.forEach(store -> { @@ -48,6 +73,10 @@ public List<StorePartResponseDto> showStoreList(@RequestAttribute("cognitoUserna @GetMapping("/{storeId}") @ResponseStatus(HttpStatus.OK) + /* + (R) Store์™€ ๊ฐ™์ด db table์— ์ €์žฅ๋˜๋Š” ์š”์†Œ๋“ค์€ ์ตœ๋Œ€ํ•œ ํด๋ผ์ด์–ธํŠธ ๋‹จ์—์„œ ๋ถ„๋ฆฌํ•˜์—ฌ ๊ฐ์ถฐ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + ์ผ๋ฐ˜์ ์œผ๋กœ Store์— ๋Œ€์‘๋˜๋Š” DTO๋ฅผ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•˜๋Š” ํŽธ์ž…๋‹ˆ๋‹ค. + */ public StoreResponseDto showStoreInfo (@RequestAttribute("storeEntity") Store store, @PathVariable String storeId){ return new StoreResponseDto(store);
Java
> Q) @RequiredArgConstructor๋ฅผ Entity์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ ์ž…๋ ฅ๋œ Property์˜ ์ˆœ์„œ๋ฅผ ๋ฐ”๊ฟจ์„ ๋•Œ ๋•Œ ๊ฐ™์€ ํƒ€์ž…์˜ property๋ผ๋ฉด ๋ฌธ์ œ๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋”๋ผ๊ณ ์š”. ์ƒ์„ฑ์ž๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ž…๋ ฅ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š์•„๋„ ์ปดํŒŒ์ผ ๊ณผ์ •์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์•„์„œ ์ž˜๋ชป๋œ ๊ฐ’์ด ๋“ค์–ด์™€๋„ ์บ์น˜ํ•  ์ˆ˜ ์—†์–ด์„œ ์•„์˜ˆ @RequiredArgConstructor๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ๋ง์ž๊ณ  ํ•˜๋Š” ๊ธ€๋„ ๋ดค์—ˆ์Šต๋‹ˆ๋‹ค. ๋ฌผ๋ก  Controller๋ผ์„œ ๊ฐ™์€ ํƒ€์ž…์˜ property๊ฐ€ ์—†์œผ๋‹ˆ๊นŒ ์—ฌ๊ธฐ์„  ๋ฌธ์ œ๊ฐ€ ์—†๊ฒ ์ง€๋งŒ, ์‹ค์ œ๋กœ @requiredargsconstructor๋ฅผ ํŽธ์˜์ƒ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋‚˜์š”? Entity์—์„œ๋งŒ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด ๋˜๋Š” ๊ฑด๊ฐ€์š”? ๋ง์”€ํ•˜์‹œ๋Š” ๋ฌธ์ œ๊ฐ€ ์–ด๋–ค ๋ฌธ์ œ์ธ์ง€ ์•Œ ์ˆ˜ ์žˆ์„๊นŒ์š”? --- > Q) Optional ์‚ฌ์šฉ์—์„œ ํ•ญ์ƒ ๊ณ ๋ฏผ์ด ๋˜์—ˆ๋Š”๋ฐ, Service ๋กœ์ง ๋‹จ์—์„œ orElseThrow()๋ฅผ ๋˜์ง€๋Š”๊ฒŒ ๋‚ซ๋‹ค๊ณ  ๋ณด์‹œ๋‚˜์š”? orElse(null)๊ณผ ๊ฐ™์€ ๋ฐฉ์‹์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? exception์„ throwํ•˜๋Š”๊ฒŒ memory cost๊ฐ€ ๋งŽ์ด ๋“ค์–ด๊ฐ„๋‹ค๊ณ  ์•Œ๊ณ  ์žˆ์–ด์„œ ๋‹ค๋ฅธ ๋ฐฉ์‹์€ ์–ด๋–ค์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. orElseThrow, orElse, orElseGet ๋“ฑ์œผ๋กœ optional์€ ๋ฐ›์€ ์ชฝ์—์„œ ์ตœ๋Œ€ํ•œ ๋น ๋ฅด๊ฒŒ ๋ฒ—๊ฒจ๋‚ด๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. optional ์ฒดํฌ ๋กœ์ง์ด ๊ดœํžˆ ์—ฌ๊ธฐ์ €๊ธฐ ๋Œ์•„๋‹ค๋‹ˆ๋ฉด ํ•ด๋‹น ๋ฐ์ดํ„ฐ๊ฐ€ nullableํ•œ ์ƒํƒœ์ž„์„ ๊ณ„์† ๊ณ ๋ คํ•ด์•ผ ํ•˜๋Š”๋ฐ, ๊ทธ๋ ‡๊ฒŒ ํ•˜๊ธฐ๋ณด๋‹ค๋Š” empty์ด๋“  ์•„๋‹ˆ๋“  ๋นจ๋ฆฌ optional wrapping์„ ์ œ๊ฑฐํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. exception์ด memory๋ฅผ ๋งŽ์ด ์žก์•„๋จน๋Š”๋‹ค๋Š” ๊ฒƒ์€ ์•„๋งˆ ์Šฌ๋ž™์— ๊ณต์œ ๋œ ์งˆ๋ฌธ์—์„œ ๋ณธ ๊ฒƒ ๊ฐ™์€๋ฐ, ๋ฉ”๋ชจ๋ฆฌ ๋ฌธ์ œ๋กœ exception์„ ๋˜์ง€๋Š” ๊ฒƒ๊นŒ์ง€ ๊ณ ๋ คํ•ด์•ผํ•  ์ˆ˜์ค€์˜ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด๋ผ๋ฉด ์ฐจ๋ผ๋ฆฌ ํ•ด๋‹น ๊ธฐ๋Šฅ์„ ๋งˆ์ดํฌ๋กœ ์„œ๋น„์Šค๋กœ ๋ถ„๋ฆฌํ•ด์„œ golang์ด๋‚˜ rust, scala ๋“ฑ ํŠนํ™” ์–ธ์–ด๋กœ ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์ด ๋งž๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. exception throw๋Š” ์ž๋ฐ”์—์„œ best practice๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ใ…Žใ…Ž ์ €๋Š” exception์„ ๋˜์ง€์ง€ ๋ชปํ•  ์ •๋„๊นŒ์ง€๋Š” ๋ณธ ์ ์ด ์—†๋Š” ๊ฒƒ ๊ฐ™๋„ค์š” --- > Q) showStoreInfo ๋ฉ”์„œ๋“œ์˜ @RequestAttribute์˜ Store ๊ฐ์ฒด๋Š” StoreCheckInterceptor๋กœ๋ถ€ํ„ฐ ๋„˜๊ฒจ๋ฐ›์€ ๊ฐ์ฒด์ž…๋‹ˆ๋‹ค. ํด๋ผ์ด์–ธํŠธ๋Š” pathvariable๋กœ storeId๋งŒ ๋˜์ ธ์ฃผ๊ณ  ์žˆ์–ด์š”. ์ธํ„ฐ์…‰ํ„ฐ๋กœ ๋ฐ›์€ Store์ธ๋ฐ๋„ DTO๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ์ข‹๋‹ค๊ณ  ๋ณด์„ธ์š”? ํ  ๊ทธ๋ ‡๊ตฐ์š”.. ์ €๋Š” ์ธํ„ฐ์…‰ํ„ฐ์—์„œ storeId๋ฅผ store๋กœ ๋ณ€ํ™˜ํ•ด์„œ controller์— ๋„˜๊ฒจ์ฃผ๋Š” ๋ถ€๋ถ„์ด ์–ด๋– ํ•œ ์ด์œ ๋กœ ์žˆ๋Š” ๊ฒƒ์ธ์ง€ ๊ถ๊ธˆํ•˜๊ธด ํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž storeId์˜ ์šฉ๋„๊ฐ€ ์ปจํŠธ๋กค๋Ÿฌ ๋‚ด์—์„œ ๋ณ€๊ฒฝ๋  ์ˆ˜๋„ ์žˆ์„ํ…๋ฐ, controller๊ฐ€ interceptor์— ๊ฐ•ํ•˜๊ฒŒ ๊ฒฐํ•ฉ๋œ ๋А๋‚Œ์ด ๋“œ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ ๋‹ค๋ฅธ ๋ถ„๋“ค์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜๋Š”์ง€ ๋“ค์–ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š”~
@@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Bucket + uuid = "F89D4C7C-1180-42EB-AF20-BEE64400FB01" + type = "1" + version = "2.0"> +</Bucket>
Unknown
์ด ํŒŒ์ผ์€ ๋ฌด์—‡์ธ๊ฐ€์š” . .? gitignore ๋กœ ์•ˆ์˜ฌ๋ฆฌ๋Š”๊ฒŒ ์ข‹์„๊ฒƒ๊ฐ€ํƒธ์š”
@@ -10,11 +10,11 @@ import UIKit class HomeViewController: UIViewController { private var feeds: [Feed] = [ - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) ] private let feedCollectionView: UICollectionView = { @@ -79,13 +79,14 @@ extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSour return cell } + // Cell Spacing func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 30.0 } // Cell size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: view.bounds.width - 32.0, height: 524) + return CGSize(width: view.bounds.width - 32.0, height: 550) } }
Swift
550์˜ ์˜๋ฏธ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š” ! ์˜๋ฏธ๊ฐ€ ์žˆ๋‹ค๋ฉด let์œผ๋กœ ๋ช…๋ช…ํ•ด์„œ ์ถ”ํ›„์— ์œ ์ง€๋ณด์ˆ˜ ๋•Œ ์•Œ์•„๋ณด๊ธฐ ์‰ฝ๊ฒŒํ•˜๋Š”๊ฒƒ์ด ์ข‹์„ ๋“ฏํ•ฉ๋‹ˆ๋‹ค ~
@@ -21,3 +21,25 @@ extension UICollectionViewCell { NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last! } } + +extension UIImage { + + func applyBlur_usingClamp(radius: CGFloat) -> UIImage { + let context = CIContext() + guard let ciImage = CIImage(image: self), + let clampFilter = CIFilter(name: "CIAffineClamp"), + let blurFilter = CIFilter(name: "CIGaussianBlur") else { + return self + } + clampFilter.setValue(ciImage, forKey: kCIInputImageKey) + blurFilter.setValue(clampFilter.outputImage, forKey: kCIInputImageKey) + blurFilter.setValue(radius, forKey: kCIInputRadiusKey) + guard let output = blurFilter.outputImage, + let cgimg = context.createCGImage(output, from: ciImage.extent) else { + return self + } + + return UIImage(cgImage: cgimg) + } +} +
Swift
Swift๋Š” ์นด๋ฉœ์ผ€์ด์Šค ~ ๐Ÿซ
@@ -21,3 +21,25 @@ extension UICollectionViewCell { NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last! } } + +extension UIImage { + + func applyBlur_usingClamp(radius: CGFloat) -> UIImage { + let context = CIContext() + guard let ciImage = CIImage(image: self), + let clampFilter = CIFilter(name: "CIAffineClamp"), + let blurFilter = CIFilter(name: "CIGaussianBlur") else { + return self + } + clampFilter.setValue(ciImage, forKey: kCIInputImageKey) + blurFilter.setValue(clampFilter.outputImage, forKey: kCIInputImageKey) + blurFilter.setValue(radius, forKey: kCIInputRadiusKey) + guard let output = blurFilter.outputImage, + let cgimg = context.createCGImage(output, from: ciImage.extent) else { + return self + } + + return UIImage(cgImage: cgimg) + } +} +
Swift
๊ณ„์† extension์ด ๋Š˜์–ด๋‚  ์˜ˆ์ •์ด๋ผ๋ฉด UIImage+.swift ๋กœ ๋ณ„๋„๋กœ ๋นผ๋ฉด์–ด๋–จ๊นŒ์šฅ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
```suggestion private let feedUpperBarStackView: UIStackView = { ``` class๊ฐ€ StackView์ธ๊ฑด ๋ฐ”๋กœ ์•Œ์•„๋ณด๋ฉด ์ฝ๊ธฐ ํŽธํ• ๊ฑฐ๊ฐ™์•„์šฉ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
```suggestion ``` ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ฒŒ๋˜์—ˆ๋‹ค๋ฉด ์‚ญ์ œ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
์—ฌ๊ธฐ์— ํ•œ์ค„์”ฉ ๋„ฃ๋Š”๊ฑด ์šฐ๋””๋งŒ์˜ ์Šคํƒ€์ผ์ธ๊ฑด๊ฐ€์š”? ๊ทธ์ € ๊ถ๊ธˆ์“ฐ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
property์ด๋ฆ„๊ณผ ์ฃผ์„์ด ๊ฐ™๋‹ค๋ฉด ๊ฐ ์ฃผ์„์ด ์‚ฌ๋ผ์ ธ๋„ ๋˜์ง€ ์•Š์„๊นŒ์š” ..?
@@ -10,11 +10,11 @@ import UIKit class HomeViewController: UIViewController { private var feeds: [Feed] = [ - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) ] private let feedCollectionView: UICollectionView = { @@ -79,13 +79,14 @@ extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSour return cell } + // Cell Spacing func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 30.0 } // Cell size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: view.bounds.width - 32.0, height: 524) + return CGSize(width: view.bounds.width - 32.0, height: 550) } }
Swift
์˜๋ฏธ๋Š” ์—†์๋‹ˆ๋‹ค.. ๋ˆˆ์œผ๋กœ ๋Œ€๊ฐ• height ์Ÿ€์Šต๋‹ˆ๋‹ค let์œผ๋กœ ๋ณ€์ˆ˜ ์„ ์–ธํ•˜๋Š”๊ฒƒ์€ ํ•ด๋‹น func ๋‚ด๋ถ€์— ์„ ์–ธํ•˜๋Š” ๊ฒƒ์ด ์ข‹๊ฒ ์ฃ ?
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
์œ„์— ์ฃผ์„ ๋ง์”€์ด์‹ ๊ฐ€์š”?
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
์ฃผ์„์€ ์ €์—๊ฒŒ ์ผ์ข…์˜ ์˜์—ญ ํ‘œ์‹œ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ตณ์ด ์กด์žฌํ•˜์ง€ ์•Š์•„๋„ ๋ ์ˆ˜๋„ ์žˆ์ง€๋งŒ ์—ฌ๊ธฐ ๋ญ”๊ฐ€๊ฐ€ ์žˆ๋‹ค๋ผ๋Š” ๋А๋‚Œ์ ์ธ ๋А๋‚Œ์ด๋ž„๊นŒ์š”
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
ํ‚ค์›Œ๋“œ๋ฅผ ์—ฌ๋Ÿฌ๊ฐœ ๋ถ™์—ฌ๋„ ๋˜๋Š”๊ตฐ์š”? ์ƒ๊ฐ๋„ ์•ˆํ•ด๋ดค์Šต๋‹ˆ๋‹ค
@@ -10,11 +10,11 @@ import UIKit class HomeViewController: UIViewController { private var feeds: [Feed] = [ - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) ] private let feedCollectionView: UICollectionView = { @@ -79,13 +79,14 @@ extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSour return cell } + // Cell Spacing func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 30.0 } // Cell size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: view.bounds.width - 32.0, height: 524) + return CGSize(width: view.bounds.width - 32.0, height: 550) } }
Swift
> ๋ˆˆ์œผ๋กœ ๋Œ€๊ฐ• height ์Ÿ€์Šต๋‹ˆ๋‹ค ๐Ÿค” ..????? > let์œผ๋กœ ๋ณ€์ˆ˜ ์„ ์–ธํ•˜๋Š”๊ฒƒ์€ ํ•ด๋‹น func ๋‚ด๋ถ€์— ์„ ์–ธํ•˜๋Š” ๊ฒƒ์ด ์ข‹๊ฒ ์ฃ ? ๋ฌผ๋ก ์ด์ฃ  !
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
L60๊ณผ ๊ฐ™์€ ๊ฐœํ–‰ ์ด์•ผ๊ธฐ๋“œ๋ฆฐ๊ฑฐ์˜€์–ด์š” !
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
๊ฐœ์ธ์ ์ธ ์Šคํƒ€์ผ์ด๋„ค์š” ! ๐Ÿ™†
@@ -0,0 +1,29 @@ +import ItemCard from "@/components/ItemCard"; +import styled from "styled-components"; +import { flexCenter } from "@/styles/common"; +import { Product } from "@/types/products"; +import SeaOtterVideo from "@/components/SeaOtterVideo"; + +const ItemCardList = ({ products, isLoading }: { products: Product[]; isLoading: boolean }) => { + return ( + <ItemCardWrapper> + {products.length || isLoading ? ( + products.map((product) => <ItemCard key={Math.random() * 10000} product={product} />) + ) : ( + <> + <SeaOtterVideo /> + <h2>๐Ÿฆฆ ๋ˆˆ ์”ป๊ณ  ์ฐพ์•„๋ด๋„ ์ƒํ’ˆ์ด ์—†์–ด์š”.. ใ… ใ… </h2> + </> + )} + </ItemCardWrapper> + ); +}; + +export default ItemCardList; + +const ItemCardWrapper = styled.div` + display: flex; + gap: 14px; + flex-wrap: wrap; + ${flexCenter} +`;
Unknown
์—ฌ๊ธฐ์„œ product.id ๊ฐ€ key ๊ฐ’์ด ์•„๋‹ˆ๋ผ Math.random ์œผ๋กœ ์ฃผ์‹  ์ด์œ ๊ฐ€ ๋”ฐ๋กœ ์žˆ์œผ์‹ค๊นŒ์šฉ ??
@@ -0,0 +1,15 @@ +import * as S from "@/components/Header/style"; + +export const HeaderMain = ({ children }: React.PropsWithChildren) => { + return <S.Header>{children}</S.Header>; +}; + +export const Title = ({ text }: { text: string }) => { + return <S.Title>{text}</S.Title>; +}; + +const Header = Object.assign(HeaderMain, { + Title, +}); + +export default Header;
Unknown
๋„ˆ๋ฌด ์ข‹์•„์š”~!
@@ -0,0 +1,29 @@ +import ItemCard from "@/components/ItemCard"; +import styled from "styled-components"; +import { flexCenter } from "@/styles/common"; +import { Product } from "@/types/products"; +import SeaOtterVideo from "@/components/SeaOtterVideo"; + +const ItemCardList = ({ products, isLoading }: { products: Product[]; isLoading: boolean }) => { + return ( + <ItemCardWrapper> + {products.length || isLoading ? ( + products.map((product) => <ItemCard key={Math.random() * 10000} product={product} />) + ) : ( + <> + <SeaOtterVideo /> + <h2>๐Ÿฆฆ ๋ˆˆ ์”ป๊ณ  ์ฐพ์•„๋ด๋„ ์ƒํ’ˆ์ด ์—†์–ด์š”.. ใ… ใ… </h2> + </> + )} + </ItemCardWrapper> + ); +}; + +export default ItemCardList; + +const ItemCardWrapper = styled.div` + display: flex; + gap: 14px; + flex-wrap: wrap; + ${flexCenter} +`;
Unknown
์„œ๋ฒ„์—์„œ ๊ฐ„ํ—์ ์œผ๋กœ ์ค‘๋ณต๋œ key ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์–ด์„œ ํ•œ ๋ฒˆ์”ฉ ๋™์ผํ•œ key ๊ฐ’์œผ๋กœ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๊ธฐ์— random ๊ฐ’์„ key ๋กœ ์„ค์ •ํ•ด์คฌ์–ด์š”!
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ด๋ ‡๊ฒŒ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•ด์ค„ ํ•„์š”๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
Enum ์‚ฌ์šฉ๋ฒ•์„ ๋‹ค์‹œ ๊ณต๋ถ€ํ•ด์„œ ์ ์šฉํ•ด๋ด…์‹œ๋‹ค. Switch๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐฉ์‹์œผ๋กœ์š”.
@@ -0,0 +1,11 @@ +package calculator.view; + +import java.util.Scanner; + +public class InputView { + public String formulaInput() { + Scanner scanner = new Scanner(System.in); + System.out.print("์ˆ˜์‹์„ ์ž…๋ ฅํ•˜์„ธ์š” : "); + return scanner.nextLine(); + } +} \ No newline at end of file
Java
ํด๋ž˜์Šค์— ์—ญํ• ์ด ๋‘ ๊ฐ€์ง€ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค 1. ๋ฌธ์ž์—ด์„ ๋ฐ›๋Š”๋‹ค 2. ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆˆ๋‹ค ํด๋ž˜์Šค์˜ ์ฑ…์ž„๊ณผ ์—ญํ• ์— ๋Œ€ํ•ด์„œ ์ƒ๊ฐํ•ด๋ด…์‹œ๋‹ค
@@ -0,0 +1,27 @@ +package calculator.controller; + +import calculator.model.Operator; +import calculator.util.FormulaParser; +import calculator.view.InputView; +import calculator.view.OutputView; + +public class CalculatorController { + private final Operator operator; + private final InputView inputView; + private final OutputView outputView; + private final FormulaParser formulaParser; + + public CalculatorController(Operator operator, InputView inputView, OutputView outputView, FormulaParser formulaParser) { + this.operator = operator; + this.inputView = inputView; + this.outputView = outputView; + this.formulaParser = formulaParser; + } + + public void calculatorRun() { + String formula = inputView.formulaInput(); + String[] values = formulaParser.parse(formula); + int result = operator.calculate(values); + outputView.resultOutput(result); + } +}
Java
์ด ๋ณ€์ˆ˜๊ฐ€ ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š” ๋ณ€์ˆ˜์ธ์ง€ ๋ณ€์ˆ˜๋ช…๋งŒ ๋ณด๊ณ  ์•Œ ์ˆ˜ ์žˆ๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
์ด๋ ‡๊ฒŒ ํ•ด์ค„ ๊ฑฐ๋ฉด ํ•„๋“œ์—์„œ ์ง์ ‘์ ์œผ๋กœ ์„ ์–ธํ•ด์ฃผ๋Š” ๊ฒƒ์ด ๋” ๊น”๋”ํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ด ๋ฉ”์†Œ๋“œ๊ฐ€ static ๋ฉ”์†Œ๋“œ์—ฌ์•ผ๋งŒ ํ•˜๋Š” ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”?
@@ -0,0 +1,11 @@ +package calculator.view; + +import java.util.Scanner; + +public class InputView { + public String formulaInput() { + Scanner scanner = new Scanner(System.in); + System.out.print("์ˆ˜์‹์„ ์ž…๋ ฅํ•˜์„ธ์š” : "); + return scanner.nextLine(); + } +} \ No newline at end of file
Java
FormulaParser ํด๋ž˜์Šค์— ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ„๋Š” ์—ญํ• ์„ ๋ถ„ํ• ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package calculator.controller; + +import calculator.model.Operator; +import calculator.util.FormulaParser; +import calculator.view.InputView; +import calculator.view.OutputView; + +public class CalculatorController { + private final Operator operator; + private final InputView inputView; + private final OutputView outputView; + private final FormulaParser formulaParser; + + public CalculatorController(Operator operator, InputView inputView, OutputView outputView, FormulaParser formulaParser) { + this.operator = operator; + this.inputView = inputView; + this.outputView = outputView; + this.formulaParser = formulaParser; + } + + public void calculatorRun() { + String formula = inputView.formulaInput(); + String[] values = formulaParser.parse(formula); + int result = operator.calculate(values); + outputView.resultOutput(result); + } +}
Java
calculatorRun์œผ๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ง€์ •๋œ ์—ฐ์‚ฐ์ž๋ฅผ ์ œ์™ธํ•œ ๋‹ค๋ฅธ ๊ธฐํ˜ธ๋ฅผ ์ž…๋ ฅํ–ˆ์„ ๊ฒฝ์šฐ์— ์ถœ๋ ฅํ•˜๋„๋ก ํ–ˆ์ง€๋งŒ ๊ณ„์‚ฐ๊ธฐ์˜ ๊ฒฝ์šฐ ๋”ฐ๋กœ ์—†์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
OperatorType์˜ ๊ธฐ๋Šฅ์„ ์ˆ˜์ •ํ•˜๋ฉด์„œ Operator์˜ ๊ธฐ๋Šฅ๊ณผ ์ค‘๋ณต๋˜๊ธฐ์— ์‚ญ์ œํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
๊ฐ์ฒด๋ฅผ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š์•„์„œ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๊ณ  static๋ฉ”์†Œ๋“œ๋กœ ์„ ์–ธํ•˜๋ฉด ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ์—†์ด ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
BiFunction ํ•„๋“œ๋ฅผ ํ™œ์šฉํ•˜์—ฌ Switch๋ฌธ ์—†์ด ์—ฐ์‚ฐ์„ ์ฒ˜๋ฆฌ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package calculator.controller; + +import calculator.model.Operator; +import calculator.util.FormulaParser; +import calculator.view.InputView; +import calculator.view.OutputView; + +public class CalculatorController { + private final Operator operator; + private final InputView inputView; + private final OutputView outputView; + private final FormulaParser formulaParser; + + public CalculatorController(Operator operator, InputView inputView, OutputView outputView, FormulaParser formulaParser) { + this.operator = operator; + this.inputView = inputView; + this.outputView = outputView; + this.formulaParser = formulaParser; + } + + public void calculatorRun() { + String formula = inputView.formulaInput(); + String[] values = formulaParser.parse(formula); + int result = operator.calculate(values); + outputView.resultOutput(result); + } +}
Java
values๋Š” ์–ด๋–ค ์šฉ๋„๋กœ ์‚ฌ์šฉ๋˜๋Š” ๋ณ€์ˆ˜์ธ๊ฐ€์š”
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
์–ด๋–ค ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐ›์•„์˜ค๋Š” ๊ฑด๊ฐ€์š”. ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋ฉ”์†Œ๋“œ ๋‚ด์—์„œ ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š”์ง€ ์•Œ ์ˆ˜ ์žˆ๋„๋ก ์ง€์–ด์ฃผ์„ธ์š”
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
static ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ด๊ฑธ ํ•„๋“œ๋กœ ์„ ์–ธํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ๋ฐ์ดํ„ฐ ์ฃผ๋„ ์„ค๊ณ„๊ฐ€ ์•„๋‹Œ ๋„๋ฉ”์ธ ์ฃผ๋„ ์„ค๊ณ„๋ฅผ ๊ณต๋ถ€ํ•ด๋ณด์„ธ
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
ํ˜„์žฌ ํ‘ธ์‰ฌํ•œ ์ฝ”๋“œ์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
values ๋งํ•œ ๊ฑฐ์—์š”
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„๋ฉ”์ธ์—์„œ view์— ์˜์กดํ•˜๋Š” ํ˜•ํƒœ๋ฅผ ๋„๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž ์ž…๋ ฅ ์ฒ˜๋ฆฌ์— ๋Œ€ํ•œ ๋ถ€๋ถ„์„ `MembershipManager` ์ฒ˜๋Ÿผ ์ปจํŠธ๋กค๋Ÿฌ๋กœ ๊บผ๋‚ด์–ด ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
์ด ๋ฉ”์„œ๋“œ์—์„œ, ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰์„ ๋ฐ›์•„, Receipt๋ฅผ ๋งŒ๋“œ๋Š”๋ฐ ์ด ๊ณผ์ •์—์„œ, ํ”„๋กœ๋ชจ์…˜์— ๋Œ€ํ•œ ๊ธฐ๋Šฅ๋“ค์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”? ์‚ฌ์šฉ์ž๊ฐ€ ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰์„ ๋ฐ›์•„ ์ €์žฅํ•˜๊ณ , ์ด ์ €์žฅ๋œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ํ”„๋กœ๋ชจ์…˜์„ ์ ์šฉํ•˜๋Š” ์ˆœ์„œ๋กœ์š”! ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด, ํ”„๋กœ๋ชจ์…˜ ์˜ˆ์™ธ์‚ฌํ•ญ์— ๋Œ€ํ•œ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ์ปจํŠธ๋กค๋Ÿฌ๋กœ ๋บ„ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค:)
@@ -0,0 +1,23 @@ +package store.constants; + +import static store.constants.StringConstants.NEW_LINE; +import static store.constants.StringConstants.ONE_SPACE; +import static store.constants.StringConstants.TAP; + +public class OutputMessages { + public static String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค." + NEW_LINE + "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค." + NEW_LINE.repeat(2); + public static String PURCHASER_LIST_FORMAT = + "===========W ํŽธ์˜์ =============" + NEW_LINE + "์ƒํ’ˆ๋ช…" + TAP.repeat(2) + "์ˆ˜๋Ÿ‰" + TAP + "๊ธˆ์•ก" + NEW_LINE; + public static String FREEBIE_LIST_FORMAT = "===========์ฆ" + TAP + "์ •=============" + NEW_LINE; + public static String AMOUNT_INFORMATION_FORMAT = "==============================" + NEW_LINE; + + public static String TOTAL_PURCHASE_AMOUNT = "์ด๊ตฌ๋งค์•ก" + TAP.repeat(2); + public static String PROMOTION_DISCOUNT = "ํ–‰์‚ฌํ• ์ธ" + TAP.repeat(3); + public static String MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญํ• ์ธ" + TAP.repeat(3); + public static String TOTAL_PRICE = "๋‚ด์‹ค๋ˆ" + TAP.repeat(3) + ONE_SPACE; + + public static String CURRENCY_UNIT = "์›"; + public static String QUANTITY_UNIT = "๊ฐœ"; + public static String OUT_OF_STOCK = "์žฌ๊ณ  ์—†์Œ"; + +}
Java
์ด๋ ‡๊ฒŒ ์ž‘์€ ํ•˜๋“œ์ฝ”๋”ฉ ๋ฌธ์ž์—ด ๊ฐ™์€ ๊ฒฝ์šฐ์— ๋Œ€ํ•ด์„œ ํ•™๊ณผ ์„ ๋ฐฐ๋‹˜๊ป˜ ๋ฌผ์–ด๋ดค๋Š”๋ฐ, ์ด๋Ÿฐ ์ž‘์€ ๋ถ€๋ถ„(๋ฌธ์ž์—ด์„ ์กฐ๋ฆฝํ•ด์•ผํ•˜๋Š” ๋ถ€๋ถ„)์€ ๋งŽ์ง€ ์•Š์œผ๋ฉด ํด๋ž˜์Šค ๋‚ด์—์„œ ์„ ์–ธํ•˜๊ณ  ์“ด๋‹ค๋Š” ์˜๊ฒฌ์„ ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„๋ฉ”์ธํด๋ž˜์Šค์˜ ์ฃผ์š”์ฑ…์ž„์€ '๋„๋ฉ”์ธ์„ ์ž˜ ํ‘œํ˜„ํ•ด๋‚ด๋Š” ๊ฒƒ'์ด๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ํ•ด๋‹น ๋„๋ฉ”์ธ ํด๋ž˜์Šค๋Š” ๋งŽ์€ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ํฌํ•จํ•˜๊ณ  ์žˆ์œผ๋ฏ€๋กœ, ๋‹จ์ผ์ฑ…์ž„์›์น™์ด ์œ„๋ฐฐ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์„œ๋น„์Šค๊ณ„์ธต์„ ๋„์ž…ํ•˜๊ฑฐ๋‚˜ ์ฑ…์ž„์„ ๋ถ„๋ฆฌํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,15 @@ +package store.constants; + +public class StringConstants { + public static final String COMMA = ","; + public static final String DASH = "-"; + public static final String NEW_LINE = "\n"; + public static final String TAP = "\t"; + public static final String OPEN_SQUARE_BRACKETS = "["; + public static final String CLOSE_SQUARE_BRACKETS = "]"; + public static final String EMPTY_STRING = ""; + public static final String ONE_SPACE = " "; + public static final String DATE_TIME_FORMATTER_PATTERN = "yyyy-MM-dd"; + public static final String NUMBER_FORMAT_WITH_COMMA = "%,d"; + +}
Java
๊ผผ๊ผผํ•œ ์ƒ์ˆ˜ ์ฒ˜๋ฆฌ! ๋ณผ ๋•Œ๋งˆ๋‹ค ๊ฐํƒ„์„ ์ž์•„๋ƒ…๋‹ˆ๋‹ค!
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ ๋ถ€๋ถ„๋„ OutputView ๋กœ ๋นผ์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
setQuantity์™€ setPromotionPeriods ๋ฉ”์„œ๋“œ๊ฐ€ ์ •์  ๋ฉ”์„œ๋“œ๋กœ ๋ณด์ด๋Š”๋ฐ ์ •์  ๋ฉ”์„œ๋“œ๋Š” ์ƒํƒœ ๋ณ€๊ฒฝ์— ์‚ฌ์šฉ๋˜๋ฉด ๊ฐ์ฒด์ง€ํ–ฅ์›์น™์— ๋งž์ง€ ์•Š์•„ ์•ˆ ์ข‹๋‹ค๊ณ  ์•Œ๊ณ ์žˆ์Šต๋‹ˆ๋‹ค Promotion ๊ฐ์ฒด๋ฅผ ์ธ์Šคํ„ด์Šคํ™”ํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„๋ฉ”์ธ์—์„œ ๋ทฐ์— ์˜์กดํ•˜๋Š” ํ˜•ํƒœ๋Š” ์ข‹์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,60 @@ +package store.domain; + +import static camp.nextstep.edu.missionutils.DateTimes.now; + +import java.time.LocalDateTime; + +public enum Promotion { + + NULL(""), + SPARKLING_BUY_TWO_GET_ONE_FREE("ํƒ„์‚ฐ2+1"), + MD_RECOMMENDATION("MD์ถ”์ฒœ์ƒํ’ˆ"), + FLASH_SALE("๋ฐ˜์งํ• ์ธ"); + + private final String promotionName; + private int buyQuantity; + private int getQuantity; + private LocalDateTime startDateTime; + private LocalDateTime endDateTime; + + Promotion(String promotionName) { + this.promotionName = promotionName; + } + + static void setQuantity(Promotion promotionName, int buyQuantity, int getQuantity) { + promotionName.buyQuantity = buyQuantity; + promotionName.getQuantity = getQuantity; + } + + static void setPromotionPeriods(Promotion promotionName, LocalDateTime startDateTime, + LocalDateTime endDateTime) { + promotionName.startDateTime = startDateTime; + promotionName.endDateTime = endDateTime; + } + + public static boolean isPromotionValid(Promotion promotionName) { + LocalDateTime now = now(); + return !now.isBefore(promotionName.startDateTime) && !now.isAfter(promotionName.endDateTime); + } + + public String getPromotionName() { + return promotionName; + } + + public int getBuyQuantity() { + return buyQuantity; + } + + public int getGetQuantity() { + return getQuantity; + } + + public LocalDateTime getStartDateTime() { + return startDateTime; + } + + public LocalDateTime getEndDateTime() { + return endDateTime; + } + +}
Java
์ €๋Š” ํ”„๋กœ๋ชจ์…˜์ด ๋™์ ์œผ๋กœ ๊ฐ’์ด ๋ฐ”๋€” ์ˆ˜ ์žˆ๋‹ค๋Š” ์กฐ๊ฑด ๋•Œ๋ฌธ์— ํ”„๋กœ๋ชจ์…˜ ๊ฐ’์ด ๋ฐ”๋€๋‹ค๋ฉด ์ฝ”๋“œ๋ฅผ ์‹น ๋‹ค ๋ฐ”๊ฟ”์ค˜์•ผ ํ•ด์„œ enum์—๋Š” ๋งž์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค ์ง€์šฐ๋‹˜์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,48 @@ +package store.domain; + +import static store.constants.NumberConstants.SINGLE_PRODUCT_QUANTITY; + +import java.util.ArrayList; +import java.util.List; +import store.exception.ProductNotExistException; + +public class StoreHouse { + + private final List<Product> productList = new ArrayList<>(); + + + public void buy(Product product, int quantity) { + product.sell(quantity); + } + + public List<Product> findProductByName(String productName) { + List<Product> filteredProduct = productList.stream() + .filter(product -> product.getName().equals(productName)) + .toList(); + + if (filteredProduct.isEmpty()) { + throw new ProductNotExistException(); + } + + return filteredProduct; + } + + public boolean checkRegularPricePurchase(String productName) { + int count = (int) productList.stream() + .filter(product -> product.getName().equals(productName)) + .count(); + List<Product> products = findProductByName(productName); + Promotion promotionName = products.getFirst().getPromotionName(); + + return count == SINGLE_PRODUCT_QUANTITY && promotionName.equals(Promotion.NULL); + } + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } +} +
Java
์ด๋ฆ„์œผ๋กœ product๋ฅผ ์ฐพ์„๊ฑฐ๋ผ๋ฉด List<Product>๋ณด๋‹ค Map<String, Product>๋Š” ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,115 @@ +package store.io; + +import static store.constants.InputMessages.ADDITIONAL_PURCHASE_MESSAGE; +import static store.constants.InputMessages.FREEBIE_ADDITION_MESSAGE; +import static store.constants.InputMessages.INPUT_PRODUCT_NAME_AND_QUANTITY; +import static store.constants.InputMessages.MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE; +import static store.constants.InputMessages.REGULAR_PRICE_BUY_MESSAGE; +import static store.constants.StringConstants.NEW_LINE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.domain.Choice; +import store.domain.Product; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.parser.InputParser; +import store.io.parser.ProductsFileLineParser; +import store.io.parser.PromotionsFileLineParser; +import store.io.reader.FileReader; +import store.io.reader.Reader; +import store.io.writer.Writer; + +public class InputView { + + private final Reader reader; + private final Writer writer; + private final InputValidator validator; + + public InputView(Reader reader, Writer writer, InputValidator validator) { + this.reader = reader; + this.writer = writer; + this.validator = validator; + } + + public StoreHouse readProductsFileInput(String fileName) { + try { + return readProductsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private StoreHouse readProductsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + StoreHouse storeHouse = new StoreHouse(); + while ((line = reader.readLine()) != null) { + Product product = new ProductsFileLineParser(line).parseLine(); + storeHouse.addProduct(product); + } + return storeHouse; + } + + public List<PromotionInfo> readPromotionsFileInput(String fileName) { + try { + return readPromotionsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private List<PromotionInfo> readPromotionsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + List<PromotionInfo> promotionInfos = new ArrayList<>(); + while ((line = reader.readLine()) != null) { + promotionInfos.add(new PromotionsFileLineParser(line).parseLine()); + } + return promotionInfos; + } + + public List<Purchase> readProductNameAndQuantity() { + writer.write(INPUT_PRODUCT_NAME_AND_QUANTITY); + String inputProductAndQuantity = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(inputProductAndQuantity); + return new InputParser().parse(inputProductAndQuantity); + } + + public Choice readFreebieAdditionChoice(String productName) { + writer.write(String.format(FREEBIE_ADDITION_MESSAGE, productName)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readRegularPricePaymentChoice(String productName, int quantity) { + writer.write(String.format(REGULAR_PRICE_BUY_MESSAGE, productName, quantity)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readMembershipDiscountApplicationChoice() { + writer.write(MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readAdditionalPurchaseChoice() { + writer.write(ADDITIONAL_PURCHASE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } +}
Java
inputView๋Š” ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋ฐ›๋Š” UI ์—ญํ• ๋กœ, ํŒŒ์ผ์„ ์ฝ๊ณ  ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ณผ์ •์€ parser๋กœ ๋นผ์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! (ํŒŒ์ผ ์ฝ๊ธฐ๋Š” FileReader๋กœ, ํ•ด๋‹น ํŒŒ์ผ์˜ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ๋Š” parser๋กœ!) ์•„๋‹ˆ๋ฉด setup service๋ฅผ ๋งŒ๋“ค์–ด์„œ ๊ทธ๊ณณ์—์„œ setup์„ ์ง„ํ–‰ํ•˜๊ณ  controller์—์„œ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๊ทธ๋ฆฌ๊ณ  ํŒŒ์ผ ์ฝ๊ธฐ ๊ธฐ๋Šฅ์„ ์ค„ ๋‹จ์œ„๋กœ ์ฝ์–ด์™€ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ด์ง€๋งŒ, readAllLines (์ง€์šฐ๋‹˜๊ป˜์„œ ๋ฆฌ๋ทฐ ํ•ด์ฃผ์…จ๋˜!) ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ•œ๋ฒˆ์— ์ฝ์–ด์™€์„œ ์ฝ”๋“œ๋ฅผ ์ฝ์–ด์˜ค๋Š” ๋ถ€๋ถ„์„ ๋‹จ์ถ• ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ต๋‹ˆ๋‹ค!
@@ -0,0 +1,115 @@ +package store.io; + +import static store.constants.InputMessages.ADDITIONAL_PURCHASE_MESSAGE; +import static store.constants.InputMessages.FREEBIE_ADDITION_MESSAGE; +import static store.constants.InputMessages.INPUT_PRODUCT_NAME_AND_QUANTITY; +import static store.constants.InputMessages.MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE; +import static store.constants.InputMessages.REGULAR_PRICE_BUY_MESSAGE; +import static store.constants.StringConstants.NEW_LINE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.domain.Choice; +import store.domain.Product; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.parser.InputParser; +import store.io.parser.ProductsFileLineParser; +import store.io.parser.PromotionsFileLineParser; +import store.io.reader.FileReader; +import store.io.reader.Reader; +import store.io.writer.Writer; + +public class InputView { + + private final Reader reader; + private final Writer writer; + private final InputValidator validator; + + public InputView(Reader reader, Writer writer, InputValidator validator) { + this.reader = reader; + this.writer = writer; + this.validator = validator; + } + + public StoreHouse readProductsFileInput(String fileName) { + try { + return readProductsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private StoreHouse readProductsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + StoreHouse storeHouse = new StoreHouse(); + while ((line = reader.readLine()) != null) { + Product product = new ProductsFileLineParser(line).parseLine(); + storeHouse.addProduct(product); + } + return storeHouse; + } + + public List<PromotionInfo> readPromotionsFileInput(String fileName) { + try { + return readPromotionsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private List<PromotionInfo> readPromotionsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + List<PromotionInfo> promotionInfos = new ArrayList<>(); + while ((line = reader.readLine()) != null) { + promotionInfos.add(new PromotionsFileLineParser(line).parseLine()); + } + return promotionInfos; + } + + public List<Purchase> readProductNameAndQuantity() { + writer.write(INPUT_PRODUCT_NAME_AND_QUANTITY); + String inputProductAndQuantity = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(inputProductAndQuantity); + return new InputParser().parse(inputProductAndQuantity); + } + + public Choice readFreebieAdditionChoice(String productName) { + writer.write(String.format(FREEBIE_ADDITION_MESSAGE, productName)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readRegularPricePaymentChoice(String productName, int quantity) { + writer.write(String.format(REGULAR_PRICE_BUY_MESSAGE, productName, quantity)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readMembershipDiscountApplicationChoice() { + writer.write(MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readAdditionalPurchaseChoice() { + writer.write(ADDITIONAL_PURCHASE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } +}
Java
์ถ”๊ฐ€๋กœ validator์˜ empty input์„ ๊ฒ€์‚ฌํ•˜๋Š” ๋ฉ”์„œ๋“œ์˜ ๊ฒฝ์šฐ, parser์— ํฌํ•จ ์‹œํ‚ค๋Š” ๊ฒƒ์ด ์–ด๋–จ๊นŒ์š”? parser๋Š” ์ž…๋ ฅ ๊ฐ’์„ ํ•ด์„ํ•˜๊ณ , ์ ์ ˆํ•œ ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ์ฑ…์ž„์„ ๊ฐ€์ง€๋ฏ€๋กœ ์ž…๋ ฅ ๊ฐ’์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๋Š” ๊ฒƒ๋„ ๊ทธ ์ฑ…์ž„์— ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,23 @@ +package store.constants; + +import static store.constants.StringConstants.NEW_LINE; +import static store.constants.StringConstants.ONE_SPACE; +import static store.constants.StringConstants.TAP; + +public class OutputMessages { + public static String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค." + NEW_LINE + "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค." + NEW_LINE.repeat(2); + public static String PURCHASER_LIST_FORMAT = + "===========W ํŽธ์˜์ =============" + NEW_LINE + "์ƒํ’ˆ๋ช…" + TAP.repeat(2) + "์ˆ˜๋Ÿ‰" + TAP + "๊ธˆ์•ก" + NEW_LINE; + public static String FREEBIE_LIST_FORMAT = "===========์ฆ" + TAP + "์ •=============" + NEW_LINE; + public static String AMOUNT_INFORMATION_FORMAT = "==============================" + NEW_LINE; + + public static String TOTAL_PURCHASE_AMOUNT = "์ด๊ตฌ๋งค์•ก" + TAP.repeat(2); + public static String PROMOTION_DISCOUNT = "ํ–‰์‚ฌํ• ์ธ" + TAP.repeat(3); + public static String MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญํ• ์ธ" + TAP.repeat(3); + public static String TOTAL_PRICE = "๋‚ด์‹ค๋ˆ" + TAP.repeat(3) + ONE_SPACE; + + public static String CURRENCY_UNIT = "์›"; + public static String QUANTITY_UNIT = "๊ฐœ"; + public static String OUT_OF_STOCK = "์žฌ๊ณ  ์—†์Œ"; + +}
Java
์˜ค ๊ทธ๋ ‡๊ตฐ์š”. ์ฐธ๊ณ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,15 @@ +package store.constants; + +public class StringConstants { + public static final String COMMA = ","; + public static final String DASH = "-"; + public static final String NEW_LINE = "\n"; + public static final String TAP = "\t"; + public static final String OPEN_SQUARE_BRACKETS = "["; + public static final String CLOSE_SQUARE_BRACKETS = "]"; + public static final String EMPTY_STRING = ""; + public static final String ONE_SPACE = " "; + public static final String DATE_TIME_FORMATTER_PATTERN = "yyyy-MM-dd"; + public static final String NUMBER_FORMAT_WITH_COMMA = "%,d"; + +}
Java
์นญ์ฐฌ,,, ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿฅน
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋†“์นœ ๋ถ€๋ถ„ ์งš์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋ฐ›๊ณ  ํ•œ๋ฒˆ์— ๋ชจ๋“  ๊ฑธ ์ฒ˜๋ฆฌํ•˜๋ ค๊ณ  ํ–ˆ๋˜ ๊ฒŒ ์‹ค์ˆ˜์˜€๋„ค์š”.. ์ฑ…์ž„ ๋ถ„๋ฆฌ๊ฐ€ ๋ถ€์กฑํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ฆฌํŒฉํ† ๋ง์— ์ ์šฉํ•ด ๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,60 @@ +package store.domain; + +import static camp.nextstep.edu.missionutils.DateTimes.now; + +import java.time.LocalDateTime; + +public enum Promotion { + + NULL(""), + SPARKLING_BUY_TWO_GET_ONE_FREE("ํƒ„์‚ฐ2+1"), + MD_RECOMMENDATION("MD์ถ”์ฒœ์ƒํ’ˆ"), + FLASH_SALE("๋ฐ˜์งํ• ์ธ"); + + private final String promotionName; + private int buyQuantity; + private int getQuantity; + private LocalDateTime startDateTime; + private LocalDateTime endDateTime; + + Promotion(String promotionName) { + this.promotionName = promotionName; + } + + static void setQuantity(Promotion promotionName, int buyQuantity, int getQuantity) { + promotionName.buyQuantity = buyQuantity; + promotionName.getQuantity = getQuantity; + } + + static void setPromotionPeriods(Promotion promotionName, LocalDateTime startDateTime, + LocalDateTime endDateTime) { + promotionName.startDateTime = startDateTime; + promotionName.endDateTime = endDateTime; + } + + public static boolean isPromotionValid(Promotion promotionName) { + LocalDateTime now = now(); + return !now.isBefore(promotionName.startDateTime) && !now.isAfter(promotionName.endDateTime); + } + + public String getPromotionName() { + return promotionName; + } + + public int getBuyQuantity() { + return buyQuantity; + } + + public int getGetQuantity() { + return getQuantity; + } + + public LocalDateTime getStartDateTime() { + return startDateTime; + } + + public LocalDateTime getEndDateTime() { + return endDateTime; + } + +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. @slay1379๋‹˜ ๋ฆฌ๋ทฐ์—๋„ ์งง๊ฒŒ ์ž‘์„ฑํ•˜๊ธด ํ–ˆ์ง€๋งŒ ์ถ”๊ฐ€๋กœ ๋ง์”€๋“œ๋ฆฌ์ž๋ฉด ํ˜„์žฌ null์„ ์ œ์™ธํ•˜๊ณ ๋Š” ์ฝ”๋“œ์—์„œ ์ง์ ‘ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์ด ์—†์ง€๋งŒ, ๋ณ€๋™ ๊ฐ€๋Šฅ์„ฑ์ด ๋†’๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ž์—ด ํƒ€์ž…์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ํŽธ์ด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. (๋ผ๊ณ  ์ž‘์„ฑํ•˜๊ณ  ๋‹ค์‹œ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๊ฐ€ ์žˆ์—ˆ๋„ค์š”...! ^^;; ํ•˜ํ•˜)
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ์ด๋ฒˆ ๋ฏธ์…˜์—์„œ๋Š” ์ฑ…์ž„ ๋ถ„๋ฆฌ์— ๋ฏธํกํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์•„์š”. PromotionManager์„ ์‚ฌ์‹ค์ƒ ์„œ๋น„์Šค์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์—ˆ๋˜ ๊ฒƒ ๊ฐ™๊ณ , ์˜๊ฒฌ ์ฐธ๊ณ ํ•ด์„œ ๋ฆฌํŒฉํ† ๋งํ•ด๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋งž์Šต๋‹ˆ๋‹ค... ์ธ์ง€ํ•˜๊ณ  ์žˆ์œผ๋ฉด์„œ๋„ ๋‹น์žฅ ๋Œ์•„๊ฐ€๋Š” ๊ฒŒ ์šฐ์„ ์ด์—ˆ๊ธฐ์— ์“ฐ๋ ˆ๊ธฐ๋ฅผ ๋งŒ๋“ค์—ˆ๋„ค์š”ใ…‹ใ…‹ใ…‹ใ…œใ…œ ์ž…๋ ฅ ๋ฐ›๋Š” ๋ถ€๋ถ„์€ ์ „๋ถ€ ๋ฐ–์œผ๋กœ ๋นผ์„œ ๋ฆฌํŒฉํ† ๋งํ•  ์˜ˆ์ •์ž…๋‹ˆ๋‹ค! ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๊ทธ๋ ‡๊ตฐ์š”..! ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๋” ๊ณต๋ถ€ํ•ด๋ณด๊ณ , ์ฐธ๊ณ ํ•ด์„œ ๋ฆฌํŒฉํ† ๋งํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.