Skip to content

Commit

Permalink
3장: JDBC 전략 패턴의 최적화
Browse files Browse the repository at this point in the history
deleteAll() 메소드와 같이 add()를 전략 패턴 적용해보자.
add()에서는 user라는 부가정보가 필요하고, 해당 오브젝트를 받을 수 있도록 AddStatement를 생성하였다.

하지만, 두 가지 문제가 찜찜하다.
1. dao의 메소드 마다 새로운 statementStrategy 구현 클래스를 만들어야 한다.
2. 부가정보가 있는 경우 이를 위해 오브젝트를 전달받는 생성자와 이를 저장해 둘 인스턴스 변수를 번거롭게 만들어야 한다.
  • Loading branch information
kimdahyeee committed Mar 14, 2020
1 parent 1eda4e0 commit 8ba9028
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 14 deletions.
25 changes: 25 additions & 0 deletions src/main/java/com/toby/tobyspring/user/dao/AddStatement.java
@@ -0,0 +1,25 @@
package com.toby.tobyspring.user.dao;

import com.toby.tobyspring.user.domain.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class AddStatement implements StatementStrategy {
User user;

public AddStatement(User user) {
this.user = user;
}

@Override
public PreparedStatement makePreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("insert into users(id, name, password) values(?, ?, ?)");
preparedStatement.setString(1, user.getId());
preparedStatement.setString(2, user.getName());
preparedStatement.setString(3, user.getPassword());

return preparedStatement;
}
}
Expand Up @@ -4,7 +4,7 @@
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DeleteAllStrategy implements StatementStrategy {
public class DeleteAllStatement implements StatementStrategy {
@Override
public PreparedStatement makePreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement("delete from users");
Expand Down
16 changes: 3 additions & 13 deletions src/main/java/com/toby/tobyspring/user/dao/UserDao.java
Expand Up @@ -17,18 +17,8 @@ public void setDataSource(DataSource dataSource) {
}

public void add(User user) throws SQLException {
Connection connection = dataSource.getConnection();
// sql 실행
PreparedStatement preparedStatement = connection.prepareStatement("insert into users(id, name, password) values(?, ?, ?)");
preparedStatement.setString(1, user.getId());
preparedStatement.setString(2, user.getName());
preparedStatement.setString(3, user.getPassword());

preparedStatement.executeUpdate();

// 자원 회수
preparedStatement.close();
connection.close();
StatementStrategy statementStrategy = new AddStatement(user);
this.jdbcContextWithStatementStrategy(statementStrategy);
}

public User get(String id) throws SQLException {
Expand Down Expand Up @@ -95,7 +85,7 @@ public int getCount() throws SQLException {
}

public void deleteAll() throws SQLException {
StatementStrategy statementStrategy = new DeleteAllStrategy();
StatementStrategy statementStrategy = new DeleteAllStatement();
this.jdbcContextWithStatementStrategy(statementStrategy);
}

Expand Down

0 comments on commit 8ba9028

Please sign in to comment.