(사진출처 : https://www.pinterest.de/pin/383580093257311272)
Singleton pattern
을 따르는 클래스는, 생성자가 여러 차례 호출되더라도 실제로 생성되는 객체는 하나이고 최초 생성 이후에 호출된 생성자는 최초의 생성자가 생성한 객체를 리턴한다. 이와 같은 디자인 유형을 싱글턴 패턴이라고 한다. 주로 공통된 객체를 여러개 생성해서 사용하는 DBCP(DataBase Connection Pool)와 같은 상황에서 많이 사용된다
- 출처 : 위키백과사전
이전 버전의 프로젝트
2018/06/01 - [Java/Project] - Baseball member management project(+File func)
이전 포스팅에서 singleton pattern을 추가하여
데이터의 흐름을 재 구성하였습니다.
mainClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | package main; import java.io.IOException; import java.util.Scanner; import dao.daoClass; public class mainClass { // Input controller public static boolean controller(String conversion) { boolean b = true; for (int i = 0; i < conversion.length(); i++) { char c = conversion.charAt(i); if (conversion.length() != 1) { b = false; break; } if ((int) c < 49 || (int) c > 54) { b = false; break; } } return b; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Create instance of daoClass daoClass dao = new daoClass(); // 변수선언 String _chNum, ExImport; int chNum; while (true) { System.out.println(); // 개행 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.print(" 6. Exit - 프로그램 종료\n>>>"); if (!controller(_chNum = sc.next())) { System.out.println("\n입력값이 올바르지 않습니다.\n"); continue; } chNum = Integer.parseInt(_chNum); switch (chNum) { case 1: // 1. 선수등록 - 추가 dao.create(); break; case 2: // 2. 등록삭제 - 삭제 dao.delete(); break; case 3: // 3. 선수검색 - 검색 dao.search(); break; case 4: // 4. 정보수정 - 수정 dao.update(); break; case 5: // 5. 모두출력 - 출력 dao.allPrint(); break; default: // 6. Exit - 프로그램 종료 System.out.print("\n파일을 저장하시겠습니까?(y/n)\n>>>"); ExImport = sc.next(); if (ExImport.equals("y") || ExImport.equals("Y")) { dao._export(); } System.out.println("\n프로그램을 종료합니다"); System.exit(0); } } } } | cs |
daoClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | package dao; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Scanner; import file.fileClass; import singleTon.delegateClass; public class daoClass { // Create Instance Scanner sc = new Scanner(System.in); delegateClass del = delegateClass.getInstance(); createClass cre = new createClass(); readClass rea = new readClass(); updateClass upd = new updateClass(); deleateClass delete = new deleateClass(); fileClass file = new fileClass(); // Member variable private deleateClass aPlayer; // Initialize in mainProcess public daoClass() { file.importData(); } // Create public void create() { cre.insert(); } // Read public void search() { rea.search(); } // Update public void update() { upd.update(); } // Delete public void delete() { delete.delete(); } // Print All public void allPrint() { rea.PrintAll(); } // Export - 내보내기 public void _export() throws IOException { file.exportData(); } } | cs |
createClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | package dao; import java.util.Scanner; import dto.batter; import dto.pitcher; import dto.playerClass; import singleTon.delegateClass; public class createClass { // Create Instance of class Scanner sc = new Scanner(System.in); delegateClass del = delegateClass.getInstance(); // Member variable private playerClass perPlayer; // Insert - 추가 public void insert() { int backNum; String name, age, team, pos, AB = null, H = null, AVG = null, WIN = null, LOSE = null, WPCT = null; System.out.println(); // 개행 while (true) { System.out.println("등록하실 선수의 정보를 입력하시오"); System.out.print("# 등번호\n>>>"); backNum = sc.nextInt(); System.out.print("# 이름\n>>>"); name = sc.next(); System.out.print("# 나이\n>>>"); age = sc.next(); System.out.print("# 소속팀\n>>>"); team = sc.next(); System.out.print("# 포지션(bat/pit)\n>>>"); pos = sc.next(); if (pos.equals("bat")) { System.out.print("# 타수\n>>>"); AB = sc.next(); System.out.print("# 안타\n>>>"); H = sc.next(); System.out.print("# 타율\n>>>"); AVG = sc.next(); break; } else if (pos.equals("pit")) { System.out.print("# 승리\n>>>"); WIN = sc.next(); System.out.print("# 패수\n>>>"); LOSE = sc.next(); System.out.print("# 승률\n>>>"); WPCT = sc.next(); break; } else { System.out.println("\n선수입력 정보가 올바르지 않습니다."); continue; } } if (pos.equals("bat")) { perPlayer = new batter(backNum, name, age, team, pos, AB, H, AVG); del.player.put(backNum, perPlayer); } else if (pos.equals("pit")) { perPlayer = new pitcher(backNum, name, age, team, pos, WIN, LOSE, WPCT); del.player.put(backNum, perPlayer); } System.out.println("\n" + del.player.size() + " 번째 선수가 등록되었습니다"); } } | cs |
readClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | package dao; import java.util.Iterator; import java.util.Scanner; import singleTon.delegateClass; public class readClass { // Create Instance of class Scanner sc = new Scanner(System.in); delegateClass del = delegateClass.getInstance(); // Search - 검색 public void search() { System.out.println(); // 개행 System.out.print("검색하고 싶은 선수의 등번호를 입력하시오\n>>>"); int backNum = sc.nextInt(); boolean check = false; check = del.player.containsKey(new Integer(backNum)); if (check==false) { System.out.println("\n등록되지 않은 번호입니다."); return; } if (del.player.get(backNum).getPos().equals("bat")) { System.out.println("#BackNum\t#Name\t#Age\t#Team\t#Pos\t#EntryNum\t#AB\t#H\t#AVG"); System.out.println(del.player.get(backNum)); } else if (del.player.get(backNum).getPos().equals("pit")) { System.out.println("#BackNum\t#Name\t#Age\t#Team\t#Pos\t#EntryNum\t#WIN\t#LOSE\t#WPCT"); System.out.println(del.player.get(backNum)); } } // PrintAll - 모두출력 public void PrintAll() { System.out.println(); // 개행 Iterator<Integer> keys = del.player.keySet().iterator(); while (keys.hasNext()) { Integer key = keys.next(); System.out.println(del.player.get(key)); } } } | cs |
updateClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | package dao; import java.util.Scanner; import dto.batter; import dto.pitcher; import dto.playerClass; import singleTon.delegateClass; public class updateClass { // Create Instance of class Scanner sc = new Scanner(System.in); delegateClass del = delegateClass.getInstance(); // Member variable private playerClass perPlayer; // Update - 수정 public void update() { System.out.println(); // 개행 System.out.print("검색하고 싶은 선수의 등번호를 입력하시오\n>>>"); int backNum = sc.nextInt(); boolean check = false; check = del.player.containsKey(new Integer(backNum)); if (check==false) { System.out.println("\n등록되지 않은 번호입니다."); return; } if (del.player.get(backNum).getPos().equals("bat")) { System.out.println("#BackNum\t#Name\t#Age\t#Team\t#Pos\t#EntryNum\t#AB\t#H\t#AVG"); System.out.println(del.player.get(backNum)); } else if (del.player.get(backNum).getPos().equals("pit")) { System.out.println("#BackNum\t#Name\t#Age\t#Team\t#Pos\t#EntryNum\t#WIN\t#LOSE\t#WPCT"); System.out.println(del.player.get(backNum)); } System.out.print("\n찾으신 정보를 수정하고 싶으시면 'Y'아니면 'N'를 입력하시오\n>>>"); String _check = sc.next(); if (_check.equals("y") || _check.equals("Y")) { String name, age, team, pos, AB = null, H = null, AVG = null, WIN = null, LOSE = null, WPCT = null; while (true) { System.out.println("등번호 "+backNum+"번 선수의 수정할 정보를 입력하시오"); System.out.print("# 이름\n>>>"); name = sc.next(); System.out.print("# 나이\n>>>"); age = sc.next(); System.out.print("# 소속팀\n>>>"); team = sc.next(); System.out.print("# 포지션(bat/pit)\n>>>"); pos = sc.next(); if (pos.equals("bat")) { System.out.print("# 타수\n>>>"); AB = sc.next(); System.out.print("# 안타\n>>>"); H = sc.next(); System.out.print("# 타율\n>>>"); AVG = sc.next(); break; } else if (pos.equals("pit")) { System.out.print("# 승리\n>>>"); WIN = sc.next(); System.out.print("# 패수\n>>>"); LOSE = sc.next(); System.out.print("# 승률\n>>>"); WPCT = sc.next(); break; } else { System.out.println("선수입력 정보가 올바르지 않습니다."); continue; } } if (pos.equals("bat")) { perPlayer = new batter(backNum, name, age, team, pos, AB, H, AVG); del.player.put(backNum,perPlayer); } else if (pos.equals("pit")) { perPlayer = new pitcher(backNum, name, age, team, pos, WIN, LOSE, WPCT); del.player.put(backNum,perPlayer); } System.out.println("\n" + backNum + " 번째 선수가 수정되었습니다"); } } } | cs |
deleteClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | package dao; import java.util.Scanner; import singleTon.delegateClass; public class deleateClass { // Create Instance of class Scanner sc = new Scanner(System.in); delegateClass del = delegateClass.getInstance(); // Delete - 삭제 public void delete() { System.out.print("\n등록삭제를 할 선수의 등번호를 입력하시오\n>>>"); int backNum = sc.nextInt(); boolean check = false; check = del.player.containsKey(new Integer(backNum)); if (check==false) { System.out.println("\n등록되지 않은 번호입니다."); return; } if (del.player.get(backNum).getPos().equals("bat")) { System.out.println("#BackNum\t#Name\t#Age\t#Team\t#Pos\t#EntryNum\t#AB\t#H\t#AVG"); System.out.println(del.player.get(backNum)); } else if (del.player.get(backNum).getPos().equals("pit")) { System.out.println("#BackNum\t#Name\t#Age\t#Team\t#Pos\t#EntryNum\t#WIN\t#LOSE\t#WPCT"); System.out.println(del.player.get(backNum)); } System.out.print("\n찾으신 정보를 삭제하고 싶으시면 'Y'아니면 'N'를 입력하시오\n>>>"); String _check = sc.next(); if (_check.equals("y") || _check.equals("Y")) { del.player.remove(backNum); System.out.println("\n삭제되었습니다."); } else { System.out.println("\n삭제를 취소합니다."); return; } } } | cs |
playerClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | package dto; public class playerClass { // Parent of member variable private int backNum; private String name, age, team, pos; public playerClass() { } public int getBackNum() { return backNum; } public void setBackNum(int backNum) { this.backNum = backNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } public String getPos() { return pos; } public void setPos(String pos) { this.pos = pos; } @Override public String toString() { return backNum + "\t-" + name + "\t-" + age + "\t-" + team + "\t-" + pos; } public playerClass(int backNum, String name, String age, String team, String pos) { super(); this.backNum = backNum; this.name = name; this.age = age; this.team = team; this.pos = pos; } } | cs |
pitcherClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package dto; public class pitcher extends playerClass { // Child of member variable private String WIN, LOSE, WPCT; public pitcher() { } public String getWIN() { return WIN; } public void setWIN(String wIN) { WIN = wIN; } public String getLOSE() { return LOSE; } public void setLOSE(String lOSE) { LOSE = lOSE; } public String getWPCT() { return WPCT; } public void setWPCT(String wPCT) { WPCT = wPCT; } @Override public String toString() { return super.toString() + "\t-" + WIN + "\t-" + LOSE + "\t-" + WPCT; } public pitcher(int backNum, String name, String age, String team, String pos, String wIN, String lOSE, String wPCT) { super(backNum, name, age, team, pos); WIN = wIN; LOSE = lOSE; WPCT = wPCT; } } | cs |
batterClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package dto; public class batter extends playerClass { // Child of member variable private String AB, H, AVG; public batter() { } public String getAB() { return AB; } public void setAB(String aB) { AB = aB; } public String getH() { return H; } public void setH(String h) { H = h; } public String getAVG() { return AVG; } public void setAVG(String aVG) { AVG = aVG; } @Override public String toString() { return super.toString() + "\t-" + AB + "\t-" + H + "\t-" + AVG; } public batter(int backNum, String name, String age, String team, String pos, String aB, String h, String aVG) { super(backNum, name, age, team, pos); AB = aB; H = h; AVG = aVG; } } | cs |
delegateClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package singleTon; import java.util.HashMap; import dao.deleateClass; import dto.playerClass; import file.fileClass; public class delegateClass { // Table of total data private static delegateClass delegate = null; public HashMap<Integer, playerClass> player = new HashMap<Integer, playerClass>(); public HashMap<Integer, playerClass> getPlayer() { return player; } public void setPlayer(HashMap<Integer, playerClass> player) { this.player = player; } // Constructor public delegateClass() { } public static delegateClass getInstance() { if(delegate == null) { delegate = new delegateClass(); } return delegate; } } | cs |
fileClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | package file; 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 java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; import dao.deleateClass; import dao.readClass; import dto.batter; import dto.pitcher; import dto.playerClass; import singleTon.delegateClass; public class fileClass { // Create Instance of class Scanner sc = new Scanner(System.in); delegateClass del = delegateClass.getInstance(); private String fileName; // Export ---------------------------------------- // ExportData(in findedFile, writeFile) public void exportData() throws IOException { while (true) { System.out.print("\n새로운 파일을 생성하시겠습니까?(y/n)\n>>>"); String check = sc.next(); if (check.equals("n") || check.equals("N")) { File newFile = new File("d:\\tmp\\" + fileName + ".txt"); writeFile(newFile); System.out.println("\n기존 파일에 저장하였습니다."); break; } System.out.print("\n새로운 파일명을 입력하시오\n>>>"); fileName = sc.next(); boolean b = findedFile(fileName); if (b == true) { System.out.println("\n같은 파일이 존재하여 파일생성에 실패하였습니다\n"); continue; } File newFile = new File("d:\\tmp\\" + fileName + ".txt"); try { if (newFile.createNewFile() == true) { writeFile(newFile); System.out.println("\n파일을 생성하였습니다."); break; } } catch (IOException e) { System.out.println("\n예외가 발생하였음.. 파일 생성실패"); } } } // FindedFile public boolean findedFile(String fileName) { File dirFile = new File("d:\\tmp"); String fileList[] = dirFile.list(); boolean b = false; for (int i = 0; i < fileList.length; i++) { if (fileList[i].equals(fileName + ".txt") == true) { b = true; break; } } return b; } // WriteFile(in checkBeforeWriteFile) public void writeFile(File newFile) throws IOException { boolean b; b = checkBeforeWriteFile(newFile); if (b == false) { System.out.println("파일에 기입할 수 없습니다."); return; } PrintWriter pw; String temp; pw = new PrintWriter(new BufferedWriter(new FileWriter(newFile))); Iterator<Integer> keys = del.player.keySet().iterator(); while (keys.hasNext()) { Integer key = keys.next(); temp = del.player.get(key).toString(); pw.println(temp); } pw.close(); } // CheckBeforWriteFile public boolean checkBeforeWriteFile(File fileName) { if (fileName.canWrite()) { return true; } return false; } // Import ---------------------------------------- // ImportData(in readFile) public void importData() { String name, age, team, pos, AB = null, H = null, AVG = null, WIN = null, LOSE = null, WPCT = null; String ExImport; int backNum; while (true) { System.out.print("\n이전 파일을 불러오겠습니까?(y/n)\n>>>"); ExImport = sc.next(); if (ExImport.equals("y") || ExImport.equals("Y")) { String fileImport[] = readFile(); if (fileImport == null) { continue; } for (int i = 0; i < fileImport.length; i++) { String splits[] = fileImport[i].split("\t-"); backNum = Integer.parseInt(splits[0]); name = splits[1]; age = splits[2]; team = splits[3]; pos = splits[4]; if (pos.equals("bat")) { AB = splits[5]; H = splits[6]; AVG = splits[7]; playerClass aPlayer = new batter(backNum, name, age, team, pos, AB, H, AVG); del.player.put(backNum, aPlayer); } else if (pos.equals("pit")) { WIN = splits[5]; LOSE = splits[6]; WPCT = splits[7]; playerClass aPlayer = new pitcher(backNum, name, age, team, pos, WIN, LOSE, WPCT); del.player.put(backNum, aPlayer); } } } else if (ExImport.equals("n") || ExImport.equals("N")) { return; } else { System.out.println("\n입력값이 잘 못 되었습니다\n"); continue; } break; } } // ReadFile(in checkBeforeReadFile) public String[] readFile() { String datas[] = null; System.out.print("불러올 파일명을 입력하시오\n>>>"); fileName = sc.next(); File readFile = new File("d:\\tmp\\" + fileName + ".txt"); boolean b = checkBeforeReadFile(readFile); if (!b) { System.out.println("파일이 존재하지 않거나 읽을 수 없다"); return null; } try { BufferedReader br = new BufferedReader(new FileReader(readFile)); int count = 0; String str; while ((str = br.readLine()) != null) { count++; } br.close(); datas = new String[count]; int w = 0; br = new BufferedReader(new FileReader(readFile)); while ((str = br.readLine()) != null) { datas[w] = str; w++; } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return datas; } // CheckBeforeReadFile static boolean checkBeforeReadFile(File f) { if (f.exists()) { if (f.isFile() && f.canRead()) { return true; } } return false; } } | cs |
'오랜된 포스팅 > Java' 카테고리의 다른 글
Chat_Application_TCP_Client(+exe file) (0) | 2018.06.18 |
---|---|
Chat_Application_TCP_Server(+exe file) (0) | 2018.06.17 |
Number Baseball Game ver_02 (+G.U.I 기능추가) (0) | 2018.06.09 |
이클립스 한글 깨짐 방지 환경설정 (1) | 2018.06.07 |
Lotto program ver_01 (0) | 2018.06.03 |