모든지 기록하자!

[Java] 싱글톤을 이용한 야구선수 관리 프로그램 본문

Java

[Java] 싱글톤을 이용한 야구선수 관리 프로그램

홍크 2021. 5. 24. 21:43
728x90

위에 사진과 같은 클래스 구조에서 싱글톤 패턴을 사용해서 프로그램을 구현해보자

public class HumanDto {

	private int number;  // 선수가 공통적으로 가지고 있는 멤버변수 선언
	private String name; // 선수번호, 이름, 나이, 신장
	private int age;
	private double height;
	
	public HumanDto() {
	}

	public HumanDto(int number, String name, int age, double height) {		
		this.number = number;
		this.name = name;
		this.age = age;
		this.height = height;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getHeight() {
		return height;
	}

	public void setHeight(double height) {
		this.height = height;
	}
	
	@Override
	public String toString() { // toString을 재정의한다.
		return " number=" + number + ", name=" + name + ", age=" + age + ", height=" + height + " ";
	}
	public String outToString() { // 파일로 저장할시에 사용할 메서드 정의
		return number +"-"+ name +"-"+ age +"-"+ height +"-";
	}
	
}
public class BatterDto extends HumanDto { // 공통된 요소를 가진 HumanDto를 상속받는다.

	private int batcount; // BatterDto 클래스에서 사용할 멤버변수 선언
	private int hit;       // 타수, 안타, 타율
	private double hitAvg;
	
	public BatterDto() {
	}

	public BatterDto(int number, String name, int age, double height, int batcount, int hit, double hitAvg) {
		super(number, name, age, height); // 부모클래스 HumanDto의 매개변수를 가져온다.
		this.batcount = batcount;
		this.hit = hit;
		this.hitAvg = hitAvg;
	}

	public int getBatcount() {
		return batcount;
	}

	public void setBatcount(int batcount) {
		this.batcount = batcount;
	}

	public int getHit() {
		return hit;
	}

	public void setHit(int hit) {
		this.hit = hit;
	}

	public double getHitAvg() {
		return hitAvg;
	}

	public void setHitAvg(double hitAvg) {
		this.hitAvg = hitAvg;
	}
	


	@Override
	public String toString() { // 부모클래스에 재정의한 super.toString()를 포함해서 출력
		return "BatterDto [" + super.toString() + "batcount=" + batcount + ", hit=" + hit + ", hitAvg=" + hitAvg + "]";
	}

	@Override
	public String outToString() { // 파일저장시에 호출할 메서드 재정의
		return super.outToString()+ batcount +"-"+ hit +"-"+ hitAvg;
	}
	
}
public class PitcherDto extends HumanDto { // 공통요소인 HumanDto를 상속받는다.

	private int win;  // PitcherDto클래스에서 사용할 멤버변수 선언
	private int lose;  // 승, 패, 방어율
	private double defence;
	
	public PitcherDto() {
	}

	public PitcherDto(int number, String name, int age, double height, int win, int lose, double defence) {
		super(number, name, age, height);
		this.win = win;
		this.lose = lose;
		this.defence = defence;
	}

	public int getWin() {
		return win;
	}

	public void setWin(int win) {
		this.win = win;
	}

	public int getLose() {
		return lose;
	}

	public void setLose(int lose) {
		this.lose = lose;
	}

	public double getDefence() {
		return defence;
	}

	public void setDefence(double defence) {
		this.defence = defence;
	}
	

	@Override
	public String toString() {
		return "PitcherDto [" + super.toString() + "win=" + win + ", lose=" + lose + ", defence=" + defence + "]";
	}

	@Override
	public String outToString() {
		return super.outToString()+ win +"-"+ lose +"-"+ defence;
	}
	
}
import java.util.ArrayList;
import java.util.List;

import day10.baseballex1.HumanDto;

public class SingletonClass { // 전체적으로 사용할 SingletonClass클래스 생성

	public List<HumanDto> list = new ArrayList<HumanDto>(); 
      // 변수를 전달받을 HumanDto클래스를 ArrayList로 선언
	
	private static SingletonClass si = null; // 싱클톤 클래스는 반드시 private로 선언
	                                         // 객체생성하지 않고 사용하기위해 static으로선언
	public SingletonClass() {} //디폴트 생성자
	
	public static SingletonClass getInstance() {
		if(si == null) {  // instance가 null일경우 생성해준다.
			si = new SingletonClass();
		}
		return si;
	}
}

 

유틸클래스

public class UtilClass {

	public static int search(String name, List<HumanDto> list) { // 매개변수로 이름과 HumanDto리스트를 받는다.
		int index = -1;
		for (int i = 0; i < list.size(); i++) { 
			if(list.get(i) != null ) {
				if(name.equals(list.get(i).getName())) {
					index = i; // 매개변수로 들어온 name과 list에 존재하는 이름이 맞으면 
					break;     // 해당 index를 반환
				}
			}
		}
		return index;
	}
}

 

입력클래스

import java.util.Scanner;

import day10.baseballex1.BatterDto;
import day10.baseballex1.PitcherDto;

public class InsertClass { // 입력 클래스
	Scanner sc = new Scanner(System.in);
	private int memberNum=1001;
	
	public InsertClass() { // 싱클톤 클래스 생성
		SingletonClass si = SingletonClass.getInstance();
		
		//데이터 없는 경우
		if(si.list.isEmpty()) {
			memberNum=1001; // list가 비어있는경우 선수번호는 1001번
		}else { // 마지막번호는 list의 size-1번 
			int lastMemberNum = si.list.get(si.list.size()-1).getNumber();
			if(lastMemberNum > 0) { // 타자는 2000번부터 시작하기 때문에 
				memberNum = 1001+(lastMemberNum%1000); //1001번에서 마지막 번호를 1000으로 나눈 나머지값을 더한다.
			}
		}
		
	}
	
	public void process() {
		
		System.out.print("투수/타자 >> ");
		String position = sc.next();
		
		System.out.print("선수명 >> ");
		String name = sc.next();
		
		System.out.print("나이 >> ");
		int age = sc.nextInt();
		
		System.out.print("신장 >> ");
		double height = sc.nextDouble();
		
		SingletonClass si = SingletonClass.getInstance();
		
		if(position.equals("투수")) { // '투수'를 입력했을 경우 입력 받을 변수
			
			System.out.print("승리 >> ");
			int win = sc.nextInt();
			
			System.out.print("패전 >> ");
			int lose = sc.nextInt();
			
			System.out.print("방어율 >> ");
			double defence = sc.nextDouble();
			
			// 투수 정보를 입력받아 PitcherDto 생성자를 호출해서 list에 추가한다.
			si.list.add(new PitcherDto(memberNum,name, age, height, win, lose, defence));
			
		}else if(position.equals("타자")) {  // '타자'를 입력했을 경우 입력 받을 변수
			
			System.out.print("타수 >> ");
			int batcount = sc.nextInt();
			
			System.out.print("안타수 >> ");
			int hit = sc.nextInt();
			
			System.out.print("타율 >> ");
			double hitAvg = sc.nextDouble();
			
            // 티지 정보를 입력받아 BatterDto 생성자를 호출해서 list에 추가한다.
			si.list.add(new BatterDto(memberNum+1000,name, age, height, batcount, hit, hitAvg));
		}
		memberNum++;
	}
}

 

삭제클래스

import java.util.Scanner;


public class DeleteClass { // 삭제 클래스
	
	public DeleteClass() {}

	public void process() {
		Scanner sc = new Scanner(System.in);
		SingletonClass si = SingletonClass.getInstance();
		System.out.print("삭제할 선수명 >> ");
		String name = sc.next();
		
		int index = UtilClass.search(name, si.list); // 입력받은 이름을 매개변수로 넣어서 index에 대입
		if(index == -1) {
			System.out.println("선수의 데이터를 찾을 수 없습니다");
			return;
		}
		
		si.list.remove(index); // 해당 index번호를 받아서 list에서 삭제
		
		System.out.println("선수의 데이터를 삭제하였습니다");
	}

}

 

검색클래스

import java.util.Scanner;

import day10.baseballex1.HumanDto;

public class SelectClass {
	
	public SelectClass() {}

	public void process() {
		SingletonClass si = SingletonClass.getInstance();
		Scanner sc = new Scanner(System.in);
		int index= -1;
		System.out.print("검색할 선수명 >> ");		
		String name = sc.next();
		for (int i = 0; i <si.list.size(); i++) {
			HumanDto hd = si.list.get(i); // 입력받은 이름을 HumanDto로 형변환
				if(name.equals(hd.getName())) {
					index = i;
					break;
			}
		}
		if(index <1) {
			System.out.println("검색된 선수가 없습니다.");
			return;
		}
		System.out.println(si.list.get(index).toString()); // 해당 index에 해당하는 toString출력
	}
}

 

수정클래스

import java.util.Scanner;

import day10.baseballex1.BatterDto;
import day10.baseballex1.HumanDto;
import day10.baseballex1.PitcherDto;

public class UpdateClass {
	
	public UpdateClass() {}

	public void process() {
		Scanner sc = new Scanner(System.in);
		System.out.print("수정할 선수명 >> ");
		String name = sc.next();
		
		SingletonClass si = SingletonClass.getInstance();
		int index= -1;
		for (int i = 0; i <si.list.size(); i++) {
			HumanDto hd = si.list.get(i); // 입력받은 이름을 HumanDto로 형변환
				if(name.equals(hd.getName())) {
					index = i;
					break;
			}
		}
		if(index <1) {
			System.out.println("해당 선수가 없습니다.");
			return;
		}
		
		HumanDto hd = si.list.get(index); // 입력받은 이름이 
		if(hd instanceof BatterDto) { // BatterDto형 인지 확인해서 true면 다운캐스팅
			BatterDto bt =(BatterDto)hd; // BatterDto의 정보를 수정해서 입력
			System.out.print("타수 >> ");
			int batcount = sc.nextInt();
			
			System.out.print("안타수 >> ");
			int hit = sc.nextInt();
			
			System.out.print("타율 >> ");
			double hitAvg = sc.nextDouble();
			
			bt.setBatcount(batcount);
			bt.setHit(hit);
			bt.setHitAvg(hitAvg);
		}else if(hd instanceof PitcherDto) { // 입력받은 이름이 PitcherDto형 인지 확인
			PitcherDto pd =(PitcherDto)hd; //PitcherDto형 인지 확인해서 true면 다운캐스팅
			System.out.print("승리 >> "); // PitcherDto의 정보를 수정해서 입력
			int win = sc.nextInt();
			
			System.out.print("패전 >> ");
			int lose = sc.nextInt();
			
			System.out.print("방어율 >> ");
			double defence = sc.nextDouble();
			
			pd.setWin(win);
			pd.setLose(lose);
			pd.setDefence(defence);
		}
		System.out.println("선수의 데이터를 수정하였습니다");
	}
}

 

선수 모두 출력

public class ShowAllClass {
	
	SingletonClass si = SingletonClass.getInstance();
	
	public void allDatas() {
		for (int i = 0; i < si.list.size(); i++) {
			if(si.list.get(i) != null) {
				System.out.println(si.list.get(i).toString());
			}
		}
	}
}

 

파일클래스

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import day10.baseballex1.BatterDto;
import day10.baseballex1.HumanDto;
import day10.baseballex1.PitcherDto;

public class FileClass {

private File file;
	
	public FileClass(String filename) { // 파일= 매개변수로 받은 이름+.txt
		file = new File("c:\\tmp\\"+filename+".txt");
		
		createFile();
	}
	public void createFile() { // 파일생성
		try {
			if(file.createNewFile()) {
				System.out.println("파일 생성 성공");
			}
		} catch (IOException e) {
			System.out.println("파일 생성 실패");
		}
	}
	public void fileLoad() { // 파일 읽어오기
		SingletonClass si = SingletonClass.getInstance();
		
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			
			String str;
				while((str = br.readLine()) != null) { // 해당 파일을 한줄씩 읽어 str에 대입
					String data[] = str.split("-"); // str에 -를 제거해서 data[]에 대입
					int pos = Integer.parseInt(data[0]); // data[0]은 선수 번호
					HumanDto hman = null; // HumanDto형 변수 선언
					if(pos <2000) { // 선수번호가 2000보다 작다면 투수이다. 
						hman = new PitcherDto(Integer.parseInt(data[0]), 
								data[1], 
								Integer.parseInt(data[2]), 
								Double.parseDouble(data[3]), 
								Integer.parseInt(data[4]), 
								Integer.parseInt(data[5]), 
								Double.parseDouble(data[6]));
					} else {	 
						hman = new BatterDto(Integer.parseInt(data[0]), 
								data[1], 
								Integer.parseInt(data[2]), 
								Double.parseDouble(data[3]), 
								Integer.parseInt(data[4]), 
								Integer.parseInt(data[5]), 
								Double.parseDouble(data[6]));
					}
					si.list.add(hman); // 입력받은 정보 hman을 list에 추가
				}
				br.close();
				
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	public void fileSave() { // 파일저장
		SingletonClass si = SingletonClass.getInstance();
		try {
			PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
			
			for (int i = 0; i < si.list.size(); i++) {
				HumanDto dto = si.list.get(i);
				pw.println(dto.outToString()); // 리스트를 순회하며 재정의한 outToString으로 저장
			}
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("파일에 저장되었습니다.");
	}
	
}

 

메인클래스

import java.util.Scanner;

import day10.baseballex1.cls.DeleteClass;
import day10.baseballex1.cls.FileClass;
import day10.baseballex1.cls.InsertClass;
import day10.baseballex1.cls.SelectClass;
import day10.baseballex1.cls.ShowAllClass;
import day10.baseballex1.cls.UpdateClass;

public class MainClass {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		FileClass fc = new FileClass("lions"); // 파일이름은 매개변수로 넣은 "lions"
		fc.fileLoad();
		
		InsertClass ic = new InsertClass(); // 기능을 사용하기 위해 각각 클래스 생성
		DeleteClass dc = new DeleteClass();
		SelectClass sel = new SelectClass();
		UpdateClass uc = new UpdateClass();
		ShowAllClass sa = new ShowAllClass();
		
		
		while(true) {
			System.out.println("메뉴 >>>>>>>>>>>>>>>");		
			System.out.println("1. 선수추가");
			System.out.println("2. 선수삭제");
			System.out.println("3. 선수검색");
			System.out.println("4. 선수수정");
			System.out.println("5. 선수모두출력");
			System.out.println("6. 저장하기");
			System.out.println("7. 불러오기");
			System.out.println("8. 종료");
						
			System.out.print("입력 >> ");
			int number = sc.nextInt();
						
			switch( number ) {
				case 1:ic.process();break;
				case 2:dc.process();break;
				case 3:sel.process();break;
				case 4:uc.process();break;
				case 5:sa.allDatas();break;
				case 6:fc.fileSave();break;
				case 7:fc.fileLoad();break;
				case 8:System.exit(0);
			}
		}		
	}
}

 

 

 

728x90
Comments