: 전화번호부 항목을 나타내는 클래스
- seq, name, phone 항목 설정
- 생성자, getter/setter 설정
- 문자열 표현을 반환하는 toString() 오버라이딩
- 컬렉션에서 indexOf를 사용하기 위해서 필요한 hashcode(), equals()를 Override
import java.util.Objects;
public class PhoneVo {
private int seq;
private String name;
private String phone;
public PhoneVo() { }
public PhoneVo(int seq, String name, String phone) {
this.seq = seq;
this.name = name;
this.phone = phone;
}
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
@Override
public String toString() {
return "{seq:" + seq + ", name:" + name + ", phone:" + phone + "}";
}
// 컬렉션에서 indexOf를 사용하기 위해서 필요한 Override
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PhoneVo other = (PhoneVo) obj;
return Objects.equals(name, other.name);
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Command 인터페이스를 생성 => 기능을 분리하여 클래스로 구현
import java.util.ArrayList;
import java.util.Scanner;
import org.comstudy21.phonebook.model.PhoneVo;
public interface Command {
ArrayList<PhoneVo> phoneBookList = new ArrayList<PhoneVo>();
Scanner scan = new Scanner(System.in);
void execute(); // 추상메서드
}
: 메뉴를 표시하고 사용자에게 입력받은 번호를 반환함
- static 임포트를 통해 정적 멤버인 no에 접근 가능
- command의 execute() 추상메서드를 구현함
import static org.comstudy21.phonebook.PhoneBookMain.*;
public class Menu implements Command {
private int menu() {
System.out.println(":::: MENU ::::");
System.out.println("1.input 2.output 3.search 4.modify 5.delete 6.end");
System.out.print("Choice: ");
no = scan.nextInt();
return no;
}
@Override
public void execute() {
menu();
}
}
: 새로운 항목 입력받음
- 입력받은 값으로 PhoneVo 객체를 생성 및 리스트에 추가
- PhoneBookMian 클래스에서 seq변수 가져와 사용
- command의 execute() 추상메서드를 구현함
public class Input implements Command {
private void input() {
System.out.println(":::: INPUT ::::");
System.out.print("성명입력: ");
String name = scan.next();
System.out.print("전화번호입력: ");
String phone = scan.next();
phoneBookList.add(new PhoneVo(seq++, name, phone));
}
@Override
public void execute() {
input();
}
}
: 리스트에 저장된 내용 출력
- command의 execute() 추상메서드를 구현함
public class Output implements Command {
private void output() {
System.out.println(":::: OUTPUT ::::");
for(int i=0; i<phoneBookList.size(); i++) {
System.out.println(phoneBookList.get(i));
}
}
@Override
public void execute() {
output();
}
}
: 특정 이름을 검색하여 검색결과 출력
- command의 execute() 추상메서드를 구현함
import org.comstudy21.phonebook.model.PhoneVo;
public class Search implements Command {
private void search() {
System.out.println(":::: SEARCH ::::");
int findIdx = -1;
System.out.print("검색 할 성명 입력 : ");
String searchName = scan.next();
for (int i=0; i<phoneBookList.size(); i++) { //phoneBookList를 순회하여 찾음
PhoneVo phoneVo = phoneBookList.get(i);
if(searchName.equals(phoneVo.getName())) {
System.out.println(searchName + "은 " + i + "번째에 있습니다.");
findIdx = i;
}
}
// 반복문이 끝나고 findIdx가 -1이면 검색 결과가 없음
if(findIdx != -1) {
System.out.println(phoneBookList.get(findIdx)); // 해당 인덱스의 객체 출력
} else {
System.out.println("검색결과가 없습니다.");
}
}
@Override
public void execute() {
search();
}
}
: 특정 이름을 검색하여 해당 이름의 전화번호를 수정함
- indexOf 메서드는 PhoneVo 클래스에서 hashCode()와 equals() 메서드가 구현되어 있어야 사용 가능함
- command의 execute() 추상메서드를 구현함
public class Modify implements Command {
//indexOf를 사용하기 위해 PhoneVo에서 hashCode, equals 오버라이딩 필요
private void modify() {
System.out.println(":::: MODIFY ::::");
System.out.print("전화번호를 수정 할 성명 입력: ");
String searchName = scan.next();
int fIndex = phoneBookList.indexOf(new PhoneVo(0, searchName, ""));
if(fIndex == -1) {
System.out.println("검색 한 내용이 없습니다.");
return; // 메서드 기능 종료
}
System.out.println("검색 결과 : " + phoneBookList.get(fIndex));
System.out.print("새 전화번호 입력: ");
phoneBookList.get(fIndex).setPhone(scan.next()); // 새로운 전화번호를 입력받아 해당 객체의 전화번호 업데이트
}
@Override
public void execute() {
modify();
}
}
: 특정 이름을 검색하여 해당 이름의 객체 삭제 (작성예정)
: 종료 메서드
- System.exit(0);를 통해 강제 종료
- command의 execute() 추상메서드를 구현함
public class End implements Command {
private void end() {
System.out.println(":::: THE END ::::");
System.exit(0); // 프로세스 강제 종료
}
@Override
public void execute() {
end();
}
}
: 주요 흐름 관리
- 해시맵을 사용하여 key(정수형 키), Value(Command) 관리
=> 메뉴 번호를 키로 사용해 해당하는 객체를 가져올 수 있음
import static org.comstudy21.phonebook.view.Command.phoneBookList;
import java.util.HashMap;
import org.comstudy21.phonebook.model.PhoneVo;
import org.comstudy21.phonebook.view.*;
import static org.comstudy21.phonebook.view.Command.*;
public class PhoneBookMain {
public static int seq = 0; //정적 변수 선언
public static int no = 0;
public static HashMap<Integer, Command> map = new HashMap<Integer, Command>();
static { // 해시맵에 각 메뉴 변호 및 해당하는 명령 객체 초기화
map.put(0, new Menu()); // 메뉴 0번에 해당하는 Menue객체 추가
map.put(1, new Input());
map.put(2, new Output());
map.put(3, new Search());
map.put(4, new Modify());
map.put(5, new Delete());
map.put(6, new End());
}
public PhoneBookMain(int size) { // 초기화
for(int i=0; i<size; i++) {
phoneBookList.add(new PhoneVo(i, "name"+i, "010-1111-111"+i)); // 초기항목 추가
}
seq = size;
}
private void start() { // 주 실행 루프
System.out.println("[ PhoneBook App ]");
map.get(0).execute(); // Menu 실행
// 분기는 if or switch or 컬렉션을 이용
map.get(no).execute();
// 재귀호출로 반복문을 대신함
start();
}
public static void main(String[] args) {
PhoneBookMain app = new PhoneBookMain(5);
app.start();
}
}