현재 구조에서 개선되어야 할 사항

  1. DAO 메서드마다 새로운 StatementStrategy 구현 클래스를 만들어야 한다.

  2. 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);
}

변경점

장점