2019.02.07 JAVA로 DB연동하기-Service객체 사용하기(Proxy)

2019. 2. 7. 16:09JAVA

 2019.02.07 JAVA로 DB연동하기 에서의 Location.java,locationDao.java는 동일, 결과도 동일

  


Proxy Pattern

일반적으로 프록시는 다른 무언가와 이어지는 인터페이스의 역할을 하는 클래스이다. 

프록시는 어떠한 것(이를테면 네트워크 연결, 메모리 안의 커다란 객체, 파일, 또 복제할 수 없거나 

수요가 많은 리소스)과도 인터페이스의 역할을 수행할 수 있다. 



#1 LocationService.java 를 추가하여 


locationDao.java를 대신하여 동작


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
package com.example;
 
import java.util.List;
 
// Proxy(대리자) 패턴 
// -> 실제  DB작업은 DAO가 한다. 
public class LocationService {
    private locationDao locationDao = new locationDao();
    
    // 입력
    public boolean insert(Location location) {
        // 같은 행이 있으면 실패 , 없다면 성공
        boolean result = false;
        int count = locationDao.countByCityName(location.getCity());
        if(count ==0) {
            int rowCount = locationDao.insert(location);
            result = true//insert 성공
        }else {
            result = false// insert 실패 
        }
        return result;
    }//insert()
    
    // 전체 목록
    public List<Location> selectAll(){
     List<Location> list  = locationDao.selectAll();
     return list;
    }
    
    // 검색
    public Location selectByCityName(String cityName) {
     Location loc = locationDao.selectByCityName(cityName);
     return loc;
    }
}
 
cs



#2  DBLocationManager.java 

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
package com.example;
 
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
 
public class DBLocaionManager {
    LocationService locationService = new LocationService();
    private Scanner sc = new Scanner(System.in);
 
    public Scanner getSc() {
        return sc;
    }
 
    public void setSc(Scanner sc) {
        this.sc = sc;
    }
 
    public void save() {
        System.out.println("도시,경도,위도 입력");
        System.out.print(">>");
        String strInput = sc.nextLine(); // 사용자 입력값
 
        StringTokenizer st = new StringTokenizer(strInput, ","); // 입력값을 ","를 기준으로 토큰화
        String[] tokens = new String[3]; // 토큰을 담을 객체
        int count = 0// 토큰 추출 작업에 필요한 int변수 선언( while을 위한 제어변수)
 
        // 토큰 추출 작업
        while (st.hasMoreTokens()) {
            tokens[count++= st.nextToken().trim(); // trim은 양끝단의 공백을 제거
        }
        double longitude = Double.parseDouble(tokens[1]); // wrapper 작업
        double latitude = Double.parseDouble(tokens[2]);
 
        Location location = new Location(tokens[0], longitude, latitude); // location 클래스에 주입
        // Dao의 insert 메소드 호출로 대체
         boolean result = locationService.insert(location);
         if(!result) { //result == false
             System.out.println( location.getCity()+"가(은) 이미 존재");
             return;
         }else {
             System.out.println(location.getCity()+"를(을) 저장\n");
         }
 
    }// save()
 
    public void listAll() {
        System.out.println("--------------------------");
        System.out.println("Table에 있는 모든 도시 출력");
        List<Location> list =locationService.selectAll();
        for(Location loc : list) {
            System.out.println(loc);
        }
        System.out.println("--------------------------");
        
 
    }// listAll()
 
    public void cityInfo() {
        System.out.println("==============");
        System.out.println("도시 이름으로 검색하기");
        System.out.println("도시이름 >>");
        
        String cityName = sc.nextLine().trim();
        
        Location loc = locationService.selectByCityName(cityName);
        if(loc==null) {
            System.out.println(cityName+"은 없습니다.");
            return;
        }
        System.out.println(loc);
        System.out.println("");
    }// cityInfo()
 
    public static void main(String[] args) {
        DBLocaionManager manager = new DBLocaionManager();
        Scanner scan = manager.getSc();
 
        while (true) {
            System.out.println("메뉴 선택:  1.입력 , 2.전체목록 , 3.검색, 4.종료");
            System.out.println(">>");
            String menu = scan.nextLine();
 
            if (menu.equals("1")){
                manager.save();
            } else if (menu.equals("2")) {
                manager.listAll();
            } else if (menu.equals("3")) {
                manager.cityInfo();
            } else if (menu.equals("4")) {
                break;
            }
        } // while
 
        System.out.println("프로그램 종료");
 
    }
 
}
 
cs