템플릿: 고정된 작업 흐름을 가진 코드를 재사용할 수 있게 함 콜백: 템플릿 안에서 호출되는 것을 목적으로 만들어진 오브젝트

템플릿/콜백의 특징

전략 패턴의 전략 - 여러 메서드를 가진 일반적인 인터페이스를 사용할 수 있다.

템플릿/콜백 패턴의 콜백 - 보통 단일 메소드 인터페이스를 사용한다.

템플릿에서 사용되는 콜백

콜백 인터페이스

public void jdbcContextWithStatementStrategy(StatementStrategy strategy) throws SQLException{
    Connection c = null;
    PreparedStatement ps = null;

    try{
      c = dataSource.getConnection();
      ps = strategy.makePreparedStatement(c);
      ps.executeUpdate();
    } catch (SQLException e){
      throw e;
    }finally {
      if (ps!= null) { try {ps.close();} catch (SQLException e){}}
      if (c != null) { try { c.close();} catch (SQLException e){}}
    }
  }

  public void add(final User user) throws SQLException {
    jdbcContextWithStatementStrategy(
        new StatementStrategy() {
          @Override
          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;
          }
        }
    );
  }

image.png

<aside> 💡

일반적인 DI: 템플릿에 인스턴스 변수를 만들어두고 사용할 의존 오브젝트를 수정자 메서드로 받아 사용 템플릿/콜백 방식: 매번 메서드 단위로 사용할 오브젝트를 새롭게 전달받는다.

</aside>