SingleTon
- 인스턴스(객체)가 한개만 만들어지는 것
- new 명령을 외부에서 사용하지 못하게 한다.
- 리소스(자원)을 아낄 수 있다
- 데이터에 대한 일관성을 유지할 수 있다, 신뢰성을 가질 수 있음
- 클래스 만드는 방법
- 자신 class의 참조값이 저장될 변수를 private static으로 선언한다.
- 모든 생성자의 접근 제한자를 private으로 한다. (new명령 외부 사용 불가능)
- 자신 class의 인스턴스를 생성하고 반환하는 메서드를 public static으로 작성한다.
(이 메서드의 이름은 보통 getInstance로 한다.)
singleton 생성 예제
public class MySingleton {
// 1번
private static MySingleton single;
// 2번
private MySingleton() {
System.out.println("싱글톤 클래스의 생성자");
}
// 3번
public static MySingleton getInstance() {
// 1번의 변수 null이면 현재 클래스의 객체를 생성해서 1번 변수에 저장한다
// 그리고 1번의 변수값을 반환한다.
if(single==null) {
single = new MySingleton();
}
return single;
}
// 기타 이 클래스가 처리할 내용들을 작성한다.
public void displayTest() {
System.out.println("싱글톤 클래스의 메서드 호출입니다");
}
}
singleton 사용 예제
public class SingletonTest {
public static void main(String[] args) {
// MySingleton test = new MySingleton(); // 외부에서 new 명령으로 생성 불가
MySingleton test2 = MySingleton.getInstance();
MySingleton test3 = MySingleton.getInstance();
// 참조값 동일
System.out.println("test2 => "+test2); // test2 => kr.or.ddit.singleton.MySingleton@15db9742
System.out.println("test3 => "+test3); // test3 => kr.or.ddit.singleton.MySingleton@15db9742
System.out.println();
System.out.println(test2==test3); // true
System.out.println(test2.equals(test3)); // true
test2.displayTest(); // 싱글톤 클래스의 메서드 호출입니다
}
}
실제로 적용하기
더보기
MemberDaoImpl.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import kr.or.ddit.member.vo.MemberVO;
import kr.or.ddit.util.DBUtil;
public class MemberDaoImpl implements IMemberDao{
private static MemberDaoImpl dao;
private MemberDaoImpl() {
// TODO Auto-generated constructor stub
}
public static MemberDaoImpl getInstance() {
if(dao==null) {
dao = new MemberDaoImpl();
}
return dao;
}
@Override
public int insertMember(MemberVO memVo) {
Connection conn = null;
PreparedStatement pstmt = null;
int cnt = 0; // 반환값이 저장될 변수
try {
conn = DBUtil.getConnection();
String sql = "insert into mymember"
+ "(mem_id, mem_pass, mem_name, mem_tel, mem_addr) "
+ " values(?, ?, ?, ?, ?) ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, memVo.getMem_id());
pstmt.setString(2, memVo.getMem_pass());
pstmt.setString(3, memVo.getMem_name());
pstmt.setString(4, memVo.getMem_tel());
pstmt.setString(5, memVo.getMem_addr());
cnt = pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
} finally {
if(pstmt!=null) try{pstmt.close();} catch(SQLException e) {}
if(conn!=null) try{conn.close();} catch(SQLException e) {}
}
return cnt;
}
@Override
public int deleteMember(String mem_id) {
Connection conn = null;
PreparedStatement pstmt = null;
int cnt = 0; // 반환값이 저장될 변수
try {
conn = DBUtil.getConnection();
String sql = "delete from mymember where mem_id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mem_id);
cnt = pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
} finally {
if(pstmt!=null) try{pstmt.close();} catch(SQLException e) {}
if(conn!=null) try{conn.close();} catch(SQLException e) {}
}
return cnt;
}
@Override
public int updateMember(MemberVO memVo) {
Connection conn = null;
PreparedStatement pstmt = null;
int cnt = 0; // 반환값이 저장될 변수
try {
conn = DBUtil.getConnection();
String sql = "update mymember set mem_pass=?, mem_name=?, mem_tel=?, mem_addr=? where mem_id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, memVo.getMem_pass());
pstmt.setString(2, memVo.getMem_name());
pstmt.setString(3, memVo.getMem_tel());
pstmt.setString(4, memVo.getMem_addr());
pstmt.setString(5, memVo.getMem_id());
cnt = pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
} finally {
if(pstmt!=null) try{pstmt.close();} catch(SQLException e) {}
if(conn!=null) try{conn.close();} catch(SQLException e) {}
}
return cnt;
}
@Override
public List<MemberVO> getAllMember() {
List<MemberVO> list = new ArrayList<MemberVO>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select * from mymember";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
MemberVO memVo = new MemberVO();
memVo.setMem_id(rs.getString("mem_id"));
memVo.setMem_pass(rs.getString("mem_pass"));
memVo.setMem_name(rs.getString("mem_name"));
memVo.setMem_tel(rs.getString("mem_tel"));
memVo.setMem_addr(rs.getString("mem_addr"));
list.add(memVo);
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if(rs!=null) try{rs.close();} catch(SQLException e) {}
if(pstmt!=null) try{pstmt.close();} catch(SQLException e) {}
if(conn!=null) try{conn.close();} catch(SQLException e) {}
}
return list;
}
@Override
public int getMemIdCount(String mem_id) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int count = 0;
try {
conn = DBUtil.getConnection();
String sql = "select count(*) count from mymember where mem_id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mem_id);
rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt("count");
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if(rs!=null) try{rs.close();} catch(SQLException e) {}
if(pstmt!=null) try{pstmt.close();} catch(SQLException e) {}
if(conn!=null) try{conn.close();} catch(SQLException e) {}
}
return count;
}
@Override
public MemberVO getMemInfo(String mem_id) {
MemberVO memVo = new MemberVO();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int count = 0;
try {
conn = DBUtil.getConnection();
String sql = "select * from mymember where mem_id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mem_id);
rs = pstmt.executeQuery();
if (rs.next()) {
memVo.setMem_id(rs.getString("mem_id"));
memVo.setMem_pass(rs.getString("mem_pass"));
memVo.setMem_name(rs.getString("mem_name"));
memVo.setMem_tel(rs.getString("mem_tel"));
memVo.setMem_addr(rs.getString("mem_addr"));
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if(rs!=null) try{rs.close();} catch(SQLException e) {}
if(pstmt!=null) try{pstmt.close();} catch(SQLException e) {}
if(conn!=null) try{conn.close();} catch(SQLException e) {}
}
return memVo;
}
@Override
public int updateMember2(Map<String, String> paramMap) {
Connection conn = null;
PreparedStatement pstmt = null;
int cnt = 0; // 반환값이 저장될 변수
try {
conn = DBUtil.getConnection();
String sql = "update mymember set "+paramMap.get("FIELD")+"=? where mem_id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, paramMap.get("VALUE"));
pstmt.setString(2, paramMap.get("MEMID"));
cnt = pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
} finally {
if(pstmt!=null) try{pstmt.close();} catch(SQLException e) {}
if(conn!=null) try{conn.close();} catch(SQLException e) {}
}
return cnt;
}
}
MemberServiceImpl.java
import java.util.List;
import java.util.Map;
import kr.or.ddit.member.dao.IMemberDao;
import kr.or.ddit.member.dao.MemberDaoImpl;
import kr.or.ddit.member.vo.MemberVO;
public class MemberServiceImpl implements IMemberService {
private static MemberServiceImpl service;
private IMemberDao dao; // DAO객체가 저장될 변수 선언
// 생성자
private MemberServiceImpl() {
dao = MemberDaoImpl.getInstance();
}
public static MemberServiceImpl getInstance() {
if(service==null) service = new MemberServiceImpl();
return service;
}
@Override
public int insertMember(MemberVO memVo) {
return dao.insertMember(memVo);
}
@Override
public int deleteMember(String mem_id) {
return dao.deleteMember(mem_id);
}
@Override
public int updateMember(MemberVO memVo) {
return dao.updateMember(memVo);
}
@Override
public List<MemberVO> getAllMember() {
return dao.getAllMember();
}
@Override
public int getMemIdCount(String mem_id) {
return dao.getMemIdCount(mem_id);
}
@Override
public MemberVO getMemInfo(String mem_id) {
return dao.getMemInfo(mem_id);
}
@Override
public int updateMember2(Map<String, String> paramMap) {
return dao.updateMember2(paramMap);
}
}
MemberController.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.MemberVO;
public class MemberController {
private Scanner scan;
private IMemberService service;
public MemberController() {
service = MemberServiceImpl.getInstance();
scan = new Scanner(System.in);
}
public static void main(String[] args) {
new MemberController().memberStart();
}
// 시작 메서드
public void memberStart() {
while (true) {
int sel = displayMenu();
switch (sel) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
update();
break;
case 4:
update2();
break;
case 5:
update_part();
break;
case 6:
print();
break;
case 0:
System.out.println("시스템을 종료합니다");
return;
default:
break;
}
}
}
private void update2() {
String mem_id = "";
System.out.print("ID >> ");
mem_id = scan.next();
int count = service.getMemIdCount(mem_id);
if (count == 0) {
System.out.println("존재하지 않는 아이디입니다.");
return;
}
int sel = displayUpdateMenu2();
Map<String, String> paramMap = new HashMap<String, String>();
if (sel==1) {
System.out.print("PW >> ");
paramMap.put("FIELD", "mem_pass");
paramMap.put("VALUE", scan.next());
}
if (sel==2) {
System.out.print("이름 >> ");
paramMap.put("FIELD", "mem_name");
paramMap.put("VALUE", scan.next());
}
if (sel==3) {
System.out.print("전화번호 >> ");
paramMap.put("FIELD", "mem_tel");
paramMap.put("VALUE", scan.next());
}
if (sel==4) {
scan.nextLine();
System.out.print("주소 >> ");
paramMap.put("FIELD", "mem_addr");
paramMap.put("VALUE", scan.nextLine());
}
paramMap.put("MEMID", mem_id);
service.updateMember2(paramMap);
}
public int displayUpdateMenu2() {
System.out.println("업데이트할 내용을 선택해주세요");
System.out.println();
System.out.println("1. 비밀번호 수정");
System.out.println("2. 이름 수정");
System.out.println("3. 전화번호 수정");
System.out.println("4. 주소 수정");
return scan.nextInt();
}
private void update_part() {
String mem_id = "";
System.out.print("ID >> ");
mem_id = scan.next();
int count = service.getMemIdCount(mem_id);
if (count == 0) {
System.out.println("존재하지 않는 아이디입니다.");
return;
}
String sel = displayUpdateMenu();
MemberVO memVo = service.getMemInfo(mem_id);
if (sel.contains("1")) {
System.out.print("PW >> ");
memVo.setMem_pass(scan.next());
}
if (sel.contains("2")) {
System.out.print("이름 >> ");
memVo.setMem_name(scan.next());
}
if (sel.contains("3")) {
System.out.print("전화번호 >> ");
memVo.setMem_tel(scan.next());
}
if (sel.contains("4")) {
scan.nextLine();
System.out.print("주소 >> ");
memVo.setMem_addr(scan.nextLine());
}
service.updateMember(memVo);
}
public String displayUpdateMenu() {
System.out.println("업데이트할 내용을 선택해주세요");
System.out.println("중복선택이 가능합니다");
System.out.println("ex. 123 > 비밀번호/이름/전화번호 수정");
System.out.println();
System.out.println("1. 비밀번호 수정");
System.out.println("2. 이름 수정");
System.out.println("3. 전화번호 수정");
System.out.println("4. 주소 수정");
return scan.next();
}
private void print() {
List<MemberVO> list = service.getAllMember();
System.out.println("-- 전체 자료 출력 --");
System.out.println();
if (list == null || list.size() == 0) {
System.out.println("회원정보가 없습니다.");
System.out.println("메인화면으로 돌아갑니다.");
System.out.println();
return;
}
System.out.println("-------------------------------------------------");
System.out.println("회원아이디\t비밀번호\t회원이름\t전화번호\t\t주소");
System.out.println("-------------------------------------------------");
for (MemberVO memVo : list) {
System.out.println(memVo.getMem_id() + "\t" + memVo.getMem_pass() + "\t" + memVo.getMem_name() + "\t"
+ memVo.getMem_tel() + "\t" + memVo.getMem_addr());
}
System.out.println("-------------------------------------------------");
}
private void update() {
String mem_id = "";
System.out.print("ID >> ");
mem_id = scan.next();
int count = service.getMemIdCount(mem_id);
if (count == 0) {
System.out.println("존재하지 않는 아이디입니다.");
return;
}
System.out.println("변경할 정보를 입력해주세요");
MemberVO memVo = new MemberVO();
memVo.setMem_id(mem_id);
System.out.print("PW >> ");
memVo.setMem_pass(scan.next());
System.out.print("이름 >> ");
memVo.setMem_name(scan.next());
System.out.print("전화번호 >> ");
memVo.setMem_tel(scan.next());
// 버퍼 삭제
scan.nextLine();
System.out.print("주소 >> ");
memVo.setMem_addr(scan.nextLine());
service.updateMember(memVo);
}
private void delete() {
String mem_id = "";
System.out.print("ID >> ");
mem_id = scan.next();
int count = service.getMemIdCount(mem_id);
if (count == 0) {
System.out.println("존재하지 않는 아이디입니다.");
return;
}
service.deleteMember(mem_id);
System.out.println("삭제가 완료되었습니다.");
}
private void insert() {
String mem_id = "";
int count;
do {
count = 0;
System.out.print("ID >> ");
mem_id = scan.next();
count = service.getMemIdCount(mem_id);
if (count > 0) {
System.out.println("중복된 아이디입니다");
}
} while (count > 0);
MemberVO memVo = new MemberVO();
memVo.setMem_id(mem_id);
System.out.print("PW >> ");
memVo.setMem_pass(scan.next());
System.out.print("이름 >> ");
memVo.setMem_name(scan.next());
System.out.print("전화번호 >> ");
memVo.setMem_tel(scan.next());
// 버퍼 삭제
scan.nextLine();
System.out.print("주소 >> ");
memVo.setMem_addr(scan.nextLine());
service.insertMember(memVo);
}
private int displayMenu() {
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("0. 작업 끝");
System.out.print("메뉴 >> ");
int sel = scan.nextInt();
return sel;
}
}
'JAVA > HIGH JAVA' 카테고리의 다른 글
[JAVA] MyBatis (0) | 2024.05.22 |
---|---|
5/21 Homework - 게시판 만들기 (0) | 2024.05.21 |
[JAVA] javaDoc 문서 / MVC 패턴 (0) | 2024.05.20 |
[JAVA] JDBC - util생성, 활용 (0) | 2024.05.16 |
5/13 Homework - lprod테이블 추가 (0) | 2024.05.13 |