Menu
Coddy logo textTech

도서 및 사용자 모델

Coddy C# 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 70개 중 63번째.

challenge icon

챌린지

쉬움

더 풍부한 기능을 갖춘 Book 및 User 모델을 구축하여 도서관 시스템을 확장해 보겠습니다. 도서의 상태 추적, 사용자의 대출 기능, 데이터를 안전하게 유지하기 위한 적절한 캡슐화를 추가합니다.

4개의 파일 구조로 작업을 계속 진행합니다:

  • Book.cs: 고유 식별자 및 상태 추적 기능으로 Book 클래스를 확장합니다. 각 도서는 Id (string), Title (string), Author (string) 및 IsAvailable (bool, 기본값은 true)을 가져야 합니다. 대출 가능 상태를 변경하고 성공 또는 실패를 나타내는 메시지를 반환하는 Borrow()Return() 메서드를 추가합니다. 대출할 수 없는 도서를 대출하려고 시도하면 "{Title} is not available"을 반환합니다. 이미 대출 가능한 도서를 반납하려고 시도하면 "{Title} was not borrowed"를 반환합니다. 성공적인 작업은 "{Title} has been borrowed" 또는 "{Title} has been returned"을 반환해야 합니다.
  • User.cs: 대출한 도서를 추적하도록 User 클래스를 확장합니다. Name (string), MemberId (int) 및 대출한 도서 ID를 저장할 private 리스트를 포함합니다. 사용자가 현재 대출 중인 도서 수를 반환하는 BorrowedCount 읽기 전용 프로퍼티를 추가합니다. 사용자의 대출 도서를 관리하기 위해 AddBorrowedBook(string bookId)RemoveBorrowedBook(string bookId) 메서드를 포함합니다. 또한 사용자가 해당 도서를 대출했는지 여부를 bool로 반환하는 HasBook(string bookId) 메서드를 추가합니다.
  • Library.cs: Library 클래스는 도서 및 사용자 컬렉션을 유지 관리해야 합니다. 도서관 데이터를 채우기 위한 AddBook(Book book)RegisterUser(User user) 메서드를 포함합니다. 해당 ID를 가진 도서를 반환하는(찾지 못한 경우 null 반환) GetBookById(string id) 메서드와 사용자에 대해 유사하게 작동하는 GetUserById(int memberId)를 추가합니다.
  • Program.cs: 입력을 기반으로 도서관 작업을 처리하여 모든 것을 하나로 모읍니다.

다음과 같은 입력을 받게 됩니다:

  • 도서관 이름
  • 추가할 도서 수
  • 각 도서 정보: id|title|author
  • 등록할 사용자 수
  • 각 사용자 정보: name|memberId
  • 수행할 작업 수
  • 각 작업 정보: action|bookId|memberId (action은 borrow 또는 return)

각 작업에 대해 대출 또는 반납 작업의 결과를 출력합니다. 모든 작업이 끝난 후, 각 사용자의 이름과 현재 대출 중인 도서 수를 {Name}: {BorrowedCount} book(s) 형식으로 보여주는 요약 정보를 출력합니다.

예를 들어, 입력이 다음과 같다면:

Downtown Library
2
B001|Clean Code|Robert Martin
B002|Design Patterns|Gang of Four
2
Alice|101
Bob|102
4
borrow|B001|101
borrow|B002|101
borrow|B001|102
return|B001|101

출력은 다음과 같아야 합니다:

Clean Code has been borrowed
Design Patterns has been borrowed
Clean Code is not available
Clean Code has been returned
Alice: 1 book(s)
Bob: 0 book(s)

Alice가 두 권의 도서를 성공적으로 대출하지만, Bob이 Clean Code(Alice가 이미 대출 중)를 대출하려고 할 때 작업이 실패하는 것을 확인하세요. Alice가 Clean Code를 반납한 후 대출 수가 1로 줄어듭니다. 이는 모델들이 함께 작동하여 도서관 규칙을 적용하는 방식을 보여줍니다!

직접 해보기

using System;
using System.Collections.Generic;

namespace LibrarySystem
{
    class Program
    {
        public static void Main(string[] args)
        {
            // 도서관 이름 읽기
            string libraryName = Console.ReadLine();
            
            // 도서관 이름으로 Library 인스턴스 생성
            Library library = new Library(libraryName);
            
            // 책 수 읽기
            int numBooks = Convert.ToInt32(Console.ReadLine());
            
            // 책을 읽고 추가
            for (int i = 0; i < numBooks; i++)
            {
                string bookInput = Console.ReadLine();
                string[] bookParts = bookInput.Split('|');
                string bookId = bookParts[0];
                string bookTitle = bookParts[1];
                string bookAuthor = bookParts[2];
                
                Book book = new Book(bookId, bookTitle, bookAuthor);
                library.AddBook(book);
            }
            
            // 사용자 수 읽기
            int numUsers = Convert.ToInt32(Console.ReadLine());
            
            // 사용자를 읽고 등록
            List<User> usersList = new List<User>();
            for (int i = 0; i < numUsers; i++)
            {
                string userInput = Console.ReadLine();
                string[] userParts = userInput.Split('|');
                string userName = userParts[0];
                int memberId = Convert.ToInt32(userParts[1]);
                
                User user = new User(userName, memberId);
                library.RegisterUser(user);
                usersList.Add(user);
            }
            
            // 작업 수 읽기
            int numOperations = Convert.ToInt32(Console.ReadLine());
            
            // 작업 처리
            for (int i = 0; i < numOperations; i++)
            {
                string operationInput = Console.ReadLine();
                string[] opParts = operationInput.Split('|');
                string action = opParts[0];
                string bookId = opParts[1];
                int memberId = Convert.ToInt32(opParts[2]);
                
                Book book = library.GetBookById(bookId);
                User user = library.GetUserById(memberId);
                
                if (action == "borrow")
                {
                    string result = book.Borrow();
                    Console.WriteLine(result);
                    if (result.Contains("has been borrowed"))
                    {
                        user.AddBorrowedBook(bookId);
                    }
                }
                else if (action == "return")
                {
                    string result = book.Return();
                    Console.WriteLine(result);
                    if (result.Contains("has been returned"))
                    {
                        user.RemoveBorrowedBook(bookId);
                    }
                }
            }
            
            // 각 사용자에 대한 요약 출력
            foreach (User user in usersList)
            {
                Console.WriteLine($"{user.Name}: {user.BorrowedCount} book(s)");
            }
        }
    }
}

객체 지향 프로그래밍의 모든 레슨