ConnectAgent는 추상클래스

ConnectTest에서 ConnectAgent를 익명 클래스로 부름

익명클래스 - 파라미터나 리턴값이 고정돼있지 않을 때 유용

향후 쿼리 전송 및 데이터 받는데 유용.




package jdbc;


import java.sql.Connection;

import java.sql.DriverManager;


//Template Method Pattern

public abstract class ConnectAgent {

static final String path = "jdbc:oracle:thin:@thinker.ipdisk.co.kr:1521:orcl";

static final String userId = "user00";

static final String userPw = "user00";

protected Connection con;

public void execute() {

try {

makeConnection();

doJob();

} catch (Exception e) {

// TODO: handle exception

} finally {

closeAll();

}

}

protected void makeConnection() throws Exception {

con = DriverManager.getConnection(path, userId, userPw);

}

protected abstract void doJob() throws Exception;

private void closeAll() {

try { con.close(); } catch(Exception e) {}

}

}


-----------------------------------------------------------------------------------------------------


package jdbc;

//Template Method Pattern
public class ConnectTest2 implements Runnable {
public void makeConnection() throws Exception {
new ConnectAgent() { 
@Override
protected void doJob() throws Exception {
System.out.println(con);
}
}.execute();
}

@Override
public void run() {
try {
makeConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectTest2 c = new ConnectTest2();
for (int i=0; i<10; i++) {
Thread t = new Thread(c);
t.start();
}
}
}


Posted by 타다키치
,