개발일지

개발일지 16일차 -Class 역할 분리-

태운콩즙 2023. 12. 15. 17:07
728x90
반응형

Class 역할 분리하기

OooMian Class

실행이 시작되는 클래스

메뉴를 출력해주고 메뉴를 선택하면 해당 기능을 실행해줌

OooService 클래스 객체를 가지고 있고 서비스 클래스의 메서드를 호출함

package ch11_classes.ex01;

import java.util.Scanner;

public class StudentMain {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean run = true;
        int selctNo = 0;
        //StudentService 클래스 객체 선언
        StudentService studentService = new StudentService();

        while (run){
            System.out.println("-------------------------------------------");
            System.out.println("1.method1 호출 | 2.method2호출 | 3. method3 호출 | 4.method4 호출 | 5.method5 호출 | 0. 종료");
            System.out.print("선택> ");
            selctNo = scanner.nextInt();
            if (selctNo == 1){
            System.out.println("메서드 호출 전");
                studentService.method1();
                System.out.println("메서드 호출 후");
            }else if (selctNo==2){
                studentService.method2();
            } else if (selctNo ==3) {
                studentService.method3();
            } else if (selctNo == 4) {
                studentService.method4();
            } else if (selctNo == 5) {
                studentService.method5();

            } else if (selctNo == 0 ) {
                run=false;
            }

        }
    }
}

 

 

OooService Class

각 기능을 수행하기 위한 여러 메서드를 가지고 있음

OooMain 에서 호출한 메서드를 실행하고 주로 OooRepository의 메서드를 호출해줌

Main 과 Repository의 중간 역할

package ch11_classes.ex01;

import java.util.List;
import java.util.Scanner;

public class StudentService {
    // 기능들을 처리해 주는 클래스
    StudentRepository studentRepository = new StudentRepository();
    Scanner scanner = new Scanner(System.in);
    /**
     *  method name : method1
     *  parameter:x
     *  return:x
     */
    public void method1(){
        System.out.println("StudentService.method1");
        studentRepository.method1();
    }
    public void method2(){
        System.out.println("StudentService.method2");
        String str1 = "집에 가고 싶다";
        studentRepository.method2(str1);

    }

    /**
     * StudentDTO 객체를 생성하고
     * Repository 의 method3로 DTO 객체를 전달함
     */
    public void method3() {
        StudentDTO studentDTO = new StudentDTO("학생1", "20231111","qqwqq","01011111111");
        studentRepository.method3(studentDTO);
        System.out.println("studentDTO = " + studentDTO);
        System.out.println("StudentService.method3");
    }

    /**
     * Repository 로 부터 List를 리턴 받아 for문으로 출력
     */
    public void method4(){
        List<StudentDTO> studentDTOList = studentRepository.method4();
        for (StudentDTO studentDTO: studentDTOList){
            System.out.println("studentDTO = " + studentDTO);
        }
    }

    /**
     * 조회할 id 입력받고
     * id 를 repository로 전달하고
     * repository로 부터 id에 해당하는 학생 정보를 리턴받고
     * 학생 정보를 출력
     */

    public void method5(){
        System.out.println("조회할 id: ");
        Long id = scanner.nextLong();
        StudentDTO studentDTO =studentRepository.method5(id);
        if (studentDTO != null){
            // 조회결과 있음
        System.out.println("studentDTO = " + studentDTO);

        } else {
            // 조회결과 없음
            System.out.println("요청하신 정보를 찾을 수 없습니다");
        }
    }


}

 

OooRepository Class

데이터의 최종 저장 공간인 oooList를 관리하는 클래스

Service 클래스에서 호출되며, 저장(C), 조회(R), 수정(U), 삭제(D) 등의 역할을 담당하는 메서드가 있음

각각의 메서드는 처리 결과를 Service 클래스로 리턴

package ch11_classes.ex01;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class StudentRepository {
    // 모든 학생정보를 관리하는 저장소 역할의 리스트
    //저장,수정,삭제 등의 처리는 Repositorry에서만  이루어지도록 하기 위해 private
    // 값을 계속 유지하기 위해 static

    private static List<StudentDTO> studentDTOList = new ArrayList();

    public void method1() {
        System.out.println("StudentRepository.method1");
    }

    /**
     * mathod name : method2
     * parameter: String
     * return:x
     * 실행내용:전달받은 매개변수 값 출력
     */
    public void method2(String str1) {
        System.out.println("str1 = " + str1);
    }

    /**
     * method name: method3
     * parameter:StudentDTO
     * return:boolean
     * 실행내용:전달받은 DTO 객체를 List에 저장하고 결과를 리턴
     */
    public boolean method3(StudentDTO studentDTO) {
        boolean result =studentDTOList.add(studentDTO);
        return result;

    }

    /**
     * return type : List
     *
     */
    public List<StudentDTO> method4(){
        return studentDTOList;
    }

    /**
     * name:method5
     * papameter: Long
     * return:StudentDTO
     */
    public StudentDTO method5(Long id){
        //id 와 일치하는 데이터가 있으면 해당 DTO 객체를 리턴하고
        // 앖으면 null을 리턴함
        StudentDTO studentDTO = null;
        for (int i = 0; i < studentDTOList.size(); i++) {
            if (id.equals(studentDTOList.get(i).getId())){
                studentDTO = studentDTOList.get(i);
            }
        }
        return studentDTO;
    }
}

 

OooDTO Class

DTD(Data Transfer Object)

프로젝트에서 다루는 객체를 정의하는 클래스

필드, getter, setter, 생성자, toString 등을 가지고 있음

 

package ch11_classes.ex01;

public class StudentDTO {
    private Long id;
    private String studentName;
    private String studentNumber;
    private String studentMajor;
    private String studentMobile;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(String studentNumber) {
        this.studentNumber = studentNumber;
    }

    public String getStudentMajor() {
        return studentMajor;
    }

    public void setStudentMajor(String studentMajor) {
        this.studentMajor = studentMajor;
    }

    public String getStudentMobile() {
        return studentMobile;
    }

    public void setStudentMobile(String studentMobile) {
        this.studentMobile = studentMobile;
    }

    public StudentDTO() {
    }

    private static Long idValue = 1L;
    public StudentDTO(String studentName, String studentNumber, String studentMajor, String studentMobile) {
        this.id = idValue++;
        this.studentName = studentName;
        this.studentNumber = studentNumber;
        this.studentMajor = studentMajor;
        this.studentMobile = studentMobile;
    }

    @Override
    public String toString() {
        return "StudentDTO{" +
                "id=" + id +
                ", studentName='" + studentName + '\'' +
                ", studentNumber='" + studentNumber + '\'' +
                ", studentMajor='" + studentMajor + '\'' +
                ", studentMobile='" + studentMobile + '\'' +
                '}';
    }
}

 

 

<예제>

main

package ch11_classes.ex02;


import ch11_classes.ex01.StudentService;

import java.util.Scanner;
public class BookMain {

        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            boolean run = true;
            int selectNo = 0;
            // bookService 클래스 객체 선언
            BookService bookService = new BookService();

            while (run) {
                System.out.println("-----------------------------------------------------------------------------------------");
                System.out.println("1.도서등록 | 2.도서목록 | 3.도서조회(id) | 4.도서조회(제목) | 5.가격수정 | 6.도서삭제 | 7.도서검색 | 0.종료");
                System.out.println("-----------------------------------------------------------------------------------------");
                System.out.print("선택> ");
                selectNo = scan.nextInt();
                if (selectNo == 1) {
                    // 호출하는 문장 작성
                    System.out.println("도서를 등록하세요");
                    bookService.save();
                } else if (selectNo == 2) {
                    // 호출하는 문장 작성
                    bookService.findAll();
                } else if (selectNo == 3) {
                    // 호출하는 문장 작성
                    bookService.findById();
                } else if (selectNo == 4) {
                    // 호출하는 문장 작성
                    bookService.findByTitle();
                } else if (selectNo == 5) {
                    // 호출하는 문장 작성
                    bookService.update();
                } else if (selectNo == 6) {
                    // 호출하는 문장 작성
                    bookService.delete();
                } else if (selectNo == 7) {
                    bookService.search();
                } else if (selectNo == 0) {
                    run = false;
                }
            }
        }
    }

service

package ch11_classes.ex02;


import java.util.List;
import java.util.Scanner;

public class BookService {
    Scanner scanner = new Scanner(System.in);
    BookRepository bookRepository = new BookRepository();
/**
 * 도서등록 메서드
 * name: save
 * parameter: x
 * return: x
 * 실행내용
 *      스캐너로 도서명, 저자, 가격, 출판사정보를 입력받고
 *      BookDTO 객체에 담아서 Repository로 전달하여 저장이 되도록 함
 *      등록 여부를 출력한다.(등록성공 or 등록실패)
 */
public void save(){
    System.out.print("제목: ");
    String bookTitle = scanner.next();
    System.out.print("저자: ");
    String bookAuthor = scanner.next();
    System.out.print("가격: ");
    int bookPrice = scanner.nextInt();
    System.out.print("출판사: ");
    String bookPublisher = scanner.next();
    BookDTO bookDTO = new BookDTO(bookTitle,bookAuthor,bookPrice,bookPublisher);
    boolean result =  bookRepository.save(bookDTO);
    if (result){
        System.out.println("등록 성공");
    }else {
        System.out.println("등록 실패");
    }
}


/**
 * 도서목록 메서드
 * name: findAll
 * parameter: x
 * return: x
 * 실행내용
 *      Repository로 부터 목록을 리턴 받아서 목록에 있는 모든 정보를 출력
 */
public void findAll(){
    List<BookDTO> bookDTOList = bookRepository.findAll();
    for (BookDTO bookDTO:bookDTOList){
        System.out.println("bookDTO = " + bookDTO);
    }
}

/**
 * 도서조회 메서드
 * name: findById
 * parameter: x
 * return: x
 * 실행내용
 *      id를 입력받고 Repository로 부터 id에 해당 하는 도서 정보를 출력
 *      없으면 없다고 출력
 */
public void findById(){
    System.out.println("조회할 id: ");
    Long id =scanner.nextLong();
    BookDTO bookDTO = bookRepository.findById(id);
    if (bookDTO != null){
        System.out.println("bookDTO = " + bookDTO);
    }else {
        System.out.println("요청하신 정보를 찾을 수 없습니다");
    }
}

/**
 * 도서조회 메서드
 * name: findByTitle
 * parameter: x
 * return: x
 * 실행내용
 *      도서제목을 입력받고 Repository로 부터 해당 하는 도서 정보를 출력(제목이 정확히 일치하는 것만)
 *      없으면 없다고 출력
 */
public void findByTitle(){
    System.out.println("조회할 책 제목: ");
    String bookTitle = scanner.next();
    BookDTO bookDTO = bookRepository.findByTitle(bookTitle);
    if (bookDTO != null){
        System.out.println("bookDTO = " + bookDTO);
    }else {
        System.out.println("요청하신 정보를 찾을수 없습니다");
    }
}

    public void search() {
        System.out.println("검색어: ");
        String bookTitle = scanner.next();
        List<BookDTO> bookDTOList = bookRepository.sarch(bookTitle);
        if (bookDTOList.size()>0){
            for (BookDTO bookDTO:bookDTOList){
                System.out.println("bookDTO = " + bookDTO);
            }
        }else {
            //bookDTOList.size() == 0 => 결과가 없다
            System.out.println("검색 결과가 없습니다");
        }
    }

    public void update() {
    //수정할 id 를 입력 받음
        //해당 id 도서가 있다면 수정할 가격을 입력 받고 수정 처리
        // 없으면 없다고 출력
        System.out.println("수정할 id: ");
        Long id =scanner.nextLong();
        BookDTO bookDTO = bookRepository.findById(id);
        if (bookDTO != null){
            System.out.println("수정할 가격: ");
            int bookPrice =scanner.nextInt();
            boolean updateResult = bookRepository.update(id , bookPrice);
            if (updateResult){
                System.out.println("수정 성공");
            }else {
                System.out.println("수정 실패");
            }
        }else {
            System.out.println("요청하신 정보를 찾을 수 없습니다");
        }
    }

    public void delete() {
        System.out.println("삭제할 id: ");
        Long id =scanner.nextLong();
        boolean result = bookRepository.delete(id);
        if (result){
            System.out.println("삭제 성공");
        }else {
            System.out.println("삭제 실패");
        }
    }
}

repository

package ch11_classes.ex02;

import java.util.ArrayList;
import java.util.List;

public class BookRepository {
    // 도서 정보를 관리하는 bookDTOList
    private static List<BookDTO> bookDTOList = new ArrayList();

    /**
     * 도서등록 메서드
     * name: save
     * parameter: BookDTO
     * return: boolean
     * 실행내용
     *      Service로 부터 전달 받은 DTO 객체를 리스트에 저장하고 결과를 리턴
     */
    public boolean save(BookDTO bookDTO){
        return bookDTOList.add(bookDTO);
    }


    /**
     * 도서목록 메서드
     * name: findAll
     * parameter: x
     * return: List<BookDTO>
     * 실행내용
     *      Service로 부터 호출되면 리스트를 리턴
     */
    public List<BookDTO> findAll (){
        return bookDTOList;
    }

    /**
     * 도서조회 메서드
     * name: findById
     * parameter: Long
     * return: BookDTO
     * 실행내용
     *      Service로 부터 id를 전달받고 일치하는 결과를 찾아서 DTO를 리턴
     *      없으면 null 리턴
     */
    public BookDTO findById(Long id){
        BookDTO bookDTO = null;
        for (int i = 0; i < bookDTOList.size(); i++) {
            if (id.equals(bookDTOList.get(i).getId())){
                bookDTO=bookDTOList.get(i);
            }

        }
        return bookDTO;
    }

    /**
     * 도서조회 메서드
     * name: findByTitle
     * parameter: String
     * return: BookDTO
     * 실행내용
     *      Service로 부터 도서제목을 전달받고 일치하는 결과를 찾아서 DTO를 리턴
     *      없으면 null 리턴
     */
    public BookDTO findByTitle(String bookTitle){
        BookDTO bookDTO = null;
        for (int i = 0; i < bookDTOList.size(); i++) {
            if (bookTitle.equals(bookDTOList.get(i).getBookTitle())){
                bookDTO=bookDTOList.get(i);
            }

        }
        return bookDTO;
    }

    public List<BookDTO> sarch(String bookTitle) {
        // 결과를 담을 List 선언
        List<BookDTO>bookDTOS = new ArrayList<>();
        for (int i = 0; i < bookDTOList.size(); i++) {
            // 저장되어 있는 도서명에 검색어가 포함되어있으면 true
            if (bookDTOList.get(i).getBookTitle().contains(bookTitle)){
                bookDTOS.add(bookDTOList.get(i));
            }
        }
        return bookDTOS;
    }

    public boolean update(Long id, int bookPrice) {
        boolean result = false;
        for (int i = 0; i < bookDTOList.size(); i++) {
            if (id.equals(bookDTOList.get(i).getId())){
                bookDTOList.get(i).setBookPrice(bookPrice);
                result = true;
            }
        }
        return result;
    }

    public boolean delete(Long id) {
        boolean result = false;
        for (int i = 0; i < bookDTOList.size(); i++) {
            if (id.equals(bookDTOList.get(i).getId())){
                bookDTOList.remove(i);
                result = true;
            }

        }
        return result;
    }
}

DTO

package ch11_classes.ex02;

public class BookDTO {
    /**
     도서 클래스
     필드
     도서관리번호(id) - Long 타입
     도서명(bookTitle)
     저자(bookAuthor)
     가격(bookPrice)
     출판사(bookPublisher)
     필드에 대한 getter/setter
     생성자 2가지
     도서 등록은 매개변수 있는 생성자로만 할 수 있음.(id는 자동으로 하나씩 증가)
     toString method
     */
   private Long id;
    private String bookTitle;
    private String bookAuthor;
   private int bookPrice;
   private String bookPublisher;

    public void setId(Long id) {
        this.id = id;
    }

    public void setBookTitle(String bookTitle) {
        this.bookTitle = bookTitle;
    }

    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }

    public void setBookPrice(int bookPrice) {
        this.bookPrice = bookPrice;
    }

    public void setBookPublisher(String bookPublisher) {
        this.bookPublisher = bookPublisher;
    }

    public Long getId() {
        return id;
    }

    public String getBookTitle() {
        return bookTitle;
    }

    public String getBookAuthor() {
        return bookAuthor;
    }

    public int getBookPrice() {
        return bookPrice;
    }

    public String getBookPublisher() {
        return bookPublisher;
    }

    public BookDTO(){

    }
    private static Long idValue=1L;

    public BookDTO (String bookTitle , String bookAuthor , int bookPrice , String bookPublisher){
        this.id =idValue++;
        this.bookTitle = bookTitle;
        this.bookAuthor = bookAuthor;
        this.bookPrice = bookPrice;
        this.bookPublisher = bookPublisher;
    }

    @Override
    public String toString() {
        return "BookDTO{" +
                "id=" + id +
                ", bookTitle='" + bookTitle + '\'' +
                ", bookAuthor='" + bookAuthor + '\'' +
                ", bookPrice='" + bookPrice + '\'' +
                ", bookPublisher='" + bookPublisher + '\'' +
                '}';
    }
}

 

728x90
반응형