Back-End

[JAVA] 기초 공부 14 MVC-1

Minch13r 2025. 1. 23. 14:52

2025.01.23 오늘도 MVC지만 MVC에서 좀 더 결합도가 낮고 응집도가 높은 형태를 지양한다. 

  • 지금 오버로딩이 안 되니까 하나에서 해결, 하나의 C, R, U, D가 같은 메서드에서 관리 가능
  • 메서드 시그니처가 계속 바뀌면 안 좋음 다른 곳에 영향이 가니까
  • 모든 인자를 DTO로 통일하면 결합도가 낮고 응집도가 높음
  • 이렇게 하면 유지보수에 용이하다.
  • 컨트롤러에서 쓸 기본 생성인자가 필요하다.

 

  1. [낮은 결합도 높은 응집도] (M : Model, V : View, C : Controller)
    1. M CRUD 오버로딩 안됨 ⇒ 낮은 응집도 → 하나의 메서드에서 모든 로직을 관리
    2. → 높은 응집도
    b. M CRUD 메서드 시그니쳐 변화 >> C 코드도 함께 에러 발생 ⇒ 결합도가 높은 코드⇒ 속성(정보)을 DTO 내부에 저장하기 때문에 메서드 시그니쳐에 변화 X ⇒ C 코드에도 변화 X
  2. c. M CRUD 메서드 시그니쳐 중 인자를 XXXDTO로 고정

NPE(NullPointerException)은 주어가 없어서 생기는 오류

 


package day017.client;

import day017.controller.Controller;

public class Client {
    public static void main(String[] args) {
        Controller app = new Controller();

        app.start();
    }
}

package day017.controller;

import day017.model.ProductDAO;
import day017.model.ProductDTO;
import day017.view.View;
import java.util.ArrayList;

public class Controller {
    private ProductDAO model;
    private View view;
    private int realNum;

    public Controller() {
        this.model = new ProductDAO();
        this.view = new View();
        this.realNum = 1001;
    }

    public void start() {
        while(true) {
            view.menuInfo();
            int command = view.inputCommand();

            if(command == 0) {
                break;
            }
            // 제품 추가
            else if(command == 1) {
                ProductDTO dto = new ProductDTO();
                dto.setName(view.inputName());
                dto.setPrice(view.inputPrice());
                dto.setStock(view.inputStock());
                dto.setNum(this.realNum++);

                boolean flag = model.insert(dto);
                if(flag) {
                    view.printTrue();
                }
                else {
                    view.printFalse();
                }
            }
            // 전체 제품 목록
            else if(command == 2) {
                ProductDTO dto = new ProductDTO();
                dto.setCondition("전체검색");
                ArrayList<ProductDTO> datas = model.selectAll(dto);
                view.printDatas(datas);
            }
            // 제품 구매
            else if(command == 3) {
                ProductDTO dto = new ProductDTO();
                dto.setNum(view.inputNum());

                // 제품 정보 확인
                ProductDTO data = model.selectOne(dto);
                view.printData(data);

                if(data != null) {
                    dto.setStock(view.inputCount());
                    dto.setCondition("재고변경");

                    boolean flag = model.update(dto);
                    if(flag) {
                        view.printTrue();
                    }
                    else {
                        view.printFalse();
                    }
                }
            }
            // 제품 삭제
            else if(command == 4) {
                // 전체 목록 출력
                ProductDTO dto = new ProductDTO();
                dto.setCondition("전체검색");
                ArrayList<ProductDTO> datas = model.selectAll(dto);
                view.printDatas(datas);

                // 삭제할 제품 선택
                dto = new ProductDTO();
                dto.setNum(view.inputNum());

                // 선택한 제품 정보 확인
                ProductDTO data = model.selectOne(dto);
                view.printData(data);

                if(data != null) {
                    boolean flag = model.delete(dto);
                    if(flag) {
                        view.printTrue();
                    }
                    else {
                        view.printFalse();
                    }
                }
            }
        }
    }
}

package day017.model;

import day016.model.StudentDTO;

import java.util.ArrayList;

public class ProductDAO {
    ArrayList<ProductDTO> datas;
    public ProductDAO() {
        datas=new ArrayList<>();

        datas.add(new ProductDTO(1001,"콜라",1200,5));
        datas.add(new ProductDTO(1002,"사이다",1100,2));
        datas.add(new ProductDTO(1003,"커피",600,1));
    }

    public ArrayList<ProductDTO> selectAll(ProductDTO dto) {
        ArrayList<ProductDTO> datas = new ArrayList<>();
        if(dto.getCondition().equals("전체검색")) {
            for(int i=0; i<this.datas.size(); i++) {
                int num = this.datas.get(i).getNum();
                String name = this.datas.get(i).getName();
                int price = this.datas.get(i).getPrice();
                int stock = this.datas.get(i).getStock();
                datas.add(new ProductDTO(num, name, price, stock));
            }
        }
        else if(dto.getCondition().equals("이름검색")) {
            for(int i=0; i<this.datas.size(); i++) {
                if(this.datas.get(i).getName().contains(dto.getName())) {
                    int num = this.datas.get(i).getNum();
                    String name = this.datas.get(i).getName();
                    int price = this.datas.get(i).getPrice();
                    int stock = this.datas.get(i).getStock();
                    datas.add(new ProductDTO(num, name, price, stock));
                }
            }
        }
        return datas;
    }

    public ProductDTO selectOne(ProductDTO dto) {
        ProductDTO data = null;
        for(int i=0; i<this.datas.size(); i++) {
            if(dto.getNum() == this.datas.get(i).getNum()) {
                int num = this.datas.get(i).getNum();
                String name = this.datas.get(i).getName();
                int price = this.datas.get(i).getPrice();
                int stock = this.datas.get(i).getStock();
                data = new ProductDTO(num, name, price, stock);
                break;
            }
        }
        return data;
    }

    public boolean insert(ProductDTO dto) {
        try {
            int num = dto.getNum();
            String name = dto.getName();
            int price = dto.getPrice();
            int stock = dto.getStock();
            this.datas.add(new ProductDTO(num, name, price, stock));
        }
        catch(Exception e) {
            System.out.println("[MODEL 로그] : insert() 수행중에 예외발생");
            return false;
        }
        return true;
    }

    public boolean update(ProductDTO dto) {
        for(int i=0; i<this.datas.size(); i++) {
            if(this.datas.get(i).getNum() == dto.getNum()) {
                if(dto.getCondition().equals("재고변경")) {
                    int currentStock = this.datas.get(i).getStock();
                    int updateAmount = dto.getStock();
                    if(currentStock < updateAmount) {
                        return false;
                    }
                    this.datas.get(i).setStock(currentStock - updateAmount);
                    int currentCount = this.datas.get(i).getCount();
                    this.datas.get(i).setCount(currentCount + updateAmount);
                    return true;
                }
            }
        }
        return false;
    }

    public boolean delete(ProductDTO dto) {
        for(int i=0; i<this.datas.size(); i++) {
            if(dto.getNum() == this.datas.get(i).getNum()) {
                this.datas.remove(i);
                return true;
            }
        }
        return false;
    }
}

package day017.model;

public class ProductDTO {
    private int num; // PK
    private String name;
    private int price;
    private int stock;
    private int count;
    private String condition;

    public ProductDTO(){

    }

    public ProductDTO(int num, String name, int price, int stock) {
        this.num = num;
        this.name = name;
        this.price = price;
        this.stock = stock;
        this.count = 0;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public int getStock() {
        return stock;
    }
    public void setStock(int stock) {
        this.stock = stock;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public String getCondition() {
        return condition;
    }
    public void setCondition(String condition) {
        this.condition = condition;
    }

    @Override
    public String toString() {
        if(this.stock<=0) {
            return "품절상품";
        }
        return "ProductDTO [num=" + num + ", name=" + name + ", price=" + price + ", stock=" + stock + ", count="
                + count + "]";
    }
}

package day017.view;

import day017.model.ProductDTO;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class View {
    Scanner scanner;
    public View() {
        scanner=new Scanner(System.in);
    }

    public void printDatas(ArrayList<ProductDTO> datas) {
        Iterator itr=datas.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
    public void menuInfo(){
        System.out.println("1. 제품추가");
        System.out.println("2. 전체출력");
        System.out.println("3. 제품 구매");
        System.out.println("4. 제품 삭제");
        System.out.println("0. 종료");
    }

    public void printData(ProductDTO data) {
        System.out.println(data);
    }

    public void printTrue() {
        System.out.println("성공!");
    }
    public void printFalse() {
        System.out.println("실패...");
    }

    public int inputCommand() {
        System.out.print("메뉴번호입력 >> ");
        return scanner.nextInt();
    }
    public String inputName() {
        System.out.print("제품명입력 >> ");
        return scanner.next();
    }
    public int inputPrice() {
        System.out.print("가격입력 >> ");
        return scanner.nextInt();
    }
    public int inputStock() {
        System.out.print("재고입력 >> ");
        return scanner.nextInt();
    }
    public int inputNum() {
        System.out.print("번호입력 >> ");
        return scanner.nextInt();
    }
    public int inputCount() {
        System.out.print("구매수량입력 >> ");
        return scanner.nextInt();
    }
}

'Back-End' 카테고리의 다른 글

[크롤링] Jsoup과 Selenium  (3) 2025.02.01
[JAVA] 기초 공부 15 크롤링  (5) 2025.01.24
[JAVA] 기초 공부 13 MVC  (1) 2025.01.22
[JAVA] 기초 공부 12 File I/O  (2) 2025.01.21
[JAVA] 기초공부 11 제네릭과 컬렉션  (1) 2025.01.20