DAO 메서드마다 새로운 StatementStrategy
구현 클래스를 만들어야 한다.
DAO 메서드에서 StatementStrategy
에 전달할 User와 같은 부가적인 정보가 있는 경우, 오브젝트를 전달받는 생성자와 이를 저장해둘 인스턴스 변수를 번거롭게 만들어야 한다.
AddStatement 클래스를 로컬 클래스로
add()
메서드 안에 집어넣는다.
public void add(User user) throws SQLException {
class AddStatement implements StatementStrategy{
User user;
public AddStatement(User user){
this.user = user;
}
public PreparedStatement makePreparedStatement(Connection c) throws SQLException{
PreparedStatement ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");
ps.setString(1, user.getId());
ps.setString(2, user.getName());
ps.setString(3, user.getPassword());
return ps;
}
}
StatementStrategy strategy = new AddStatement(user);
jdbcContextWithStatementStrategy(strategy);
}
⇒ AddStatement
간결하게 표현하기
public void add(final User user) throws SQLException {
class AddStatement implements StatementStrategy{
public PreparedStatement makePreparedStatement(Connection c) throws SQLException{
PreparedStatement ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");
ps.setString(1, user.getId());
ps.setString(2, user.getName());
ps.setString(3, user.getPassword());
return ps;
}
}
StatementStrategy strategy = new AddStatement();
jdbcContextWithStatementStrategy(strategy);
}
변경점
AddStatement
가 생성자를 통해 객체를 받는 과정이 사라졌다.
AddStatement
는 직접 메서드 파라미터(일종의 로컬 변수)에 직접 접근한다.final
로 선언해줘야 한다.
final
로 선언해도 무방하다.