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