Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.javabom.toby.chapter3.pattern.템플릿_콜백_패턴;

import java.io.IOException;
import java.io.InputStream;

public class Calculator {
public Integer calcSum(InputStream in) throws IOException {
/*
* 콜백: 메서드에 전달되는 오브젝트. 파라미터지만 값이아니라 특정로직이다.
* 변하는 부분을 콜백으로 전달한다.
* - line, value는 컨텍스트 정보를 전달하는 매개변수이다. 콜백은 이 정보들을 참조하여 템플릿에 전달된다.
*/
LineCallback sumCallBack = (line, value) -> value + Integer.parseInt(line);
return StreamReaderTemplate.lineReadTemplate(in, sumCallBack, 0);
}

/*
익명클래스로 넣을 때 메모리 저장 시점
*/
public Integer calcMultiply(InputStream in) throws IOException {
return StreamReaderTemplate.lineReadTemplate(in, (line, value) -> value * Integer.parseInt(line), 1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.javabom.toby.chapter3.pattern.템플릿_콜백_패턴;

public interface LineCallback {
Integer doSomethingWithLine(String line, Integer value);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.javabom.toby.chapter3.pattern.템플릿_콜백_패턴;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;

public class StreamReaderTemplate {

/**
* 템플릿: Calculator 에서 행해지는 연산들에 공통으로 필요한 코드를 템플릿으로 정의한다.
* 여기서는 InputStream 에서 한줄씩 읽으며 try-catch-finally 로 묶인 일련의 과정이 속한다.
*/
public static Integer lineReadTemplate(InputStream in, LineCallback lineCallback, int initVal) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(in));
Integer res = initVal;
String line;
while ((line = br.readLine()) != null) {
res = lineCallback.doSomethingWithLine(line, res);
}
return res;
} catch (IOException e) {
System.out.println(e.getMessage());
throw e;
} finally {
if (Objects.nonNull(br)) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.javabom.toby.chapter3.pattern.템플릿_콜백_패턴;


import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

class CalculatorTest {

@DisplayName("덧셈, 곱셈, 템플릿콜백패턴")
@Test
void test() throws IOException {
Calculator calculator = new Calculator();
Integer sum = calculator.calcSum(getClass().getClassLoader().getResourceAsStream("chapter3/calcSample.txt"));
Integer multiply = calculator.calcMultiply(getClass().getClassLoader().getResourceAsStream("chapter3/calcSample.txt"));

assertThat(sum).isEqualTo(6);
assertThat(multiply).isEqualTo(6);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1
2
3
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.javabom.toby.chapter3.jdbc_템플릿_콜백_패턴;

import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

public class Chapter3UserDao {
private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public void add(TobyUser user) {
jdbcTemplate.update("INSERT INTO TOBY_USER VALUES (?, ?, ?)", user.getId(), user.getName(), user.getPassword());
}

public void get(final String id) {

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.javabom.toby.chapter3.jdbc_템플릿_콜백_패턴;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcContext {
private final DataSource dataSource;

public JdbcContext(DataSource dataSource) {
this.dataSource = dataSource;
}

/*
변하지 않는 템플릿
*/
public void workWithStatementStrategy(StatementStrategy statementStrategy) throws SQLException {
Connection connection = null;
try {
connection = dataSource.getConnection();
// 콜백 파라미터로 현재 컨텍스트의 Connection 을 넘긴다
statementStrategy.makePreparedStatement(connection).executeUpdate();
} catch (SQLException throwables) {


} finally {
connection.close();
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.javabom.toby.chapter3.jdbc_템플릿_콜백_패턴;

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

public interface StatementStrategy {
PreparedStatement makePreparedStatement(Connection c) throws SQLException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.javabom.toby.chapter3.jdbc_템플릿_콜백_패턴;

import lombok.Getter;

@Getter
public class TobyUser {
private String id;
private String name;
private String password;

public TobyUser(final String id, final String name, final String password) {
this.id = id;
this.name = name;
this.password = password;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.javabom.toby.chapter3.jdbc_템플릿_콜백_패턴;

import java.sql.SQLException;

public class UserDaoWithTemplateCallback {
private final JdbcContext jdbcContext;

public UserDaoWithTemplateCallback(JdbcContext jdbcContext) {
this.jdbcContext = jdbcContext;
}

public void deleteAll() throws SQLException {
this.jdbcContext.workWithStatementStrategy(
c -> c.prepareStatement("delete from users")); // 변하는 부분을 콜백으로 뺀다
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public UserDao userDao() {
public UserDao dataSourceUserDao() {
UserDao userDao = new UserDao();
userDao.setDataSource(dataSource());
userDao.setJdbcContext(jdbcContext());
return userDao;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
<property name="connectionMaker" ref="localDBConnectionMaker"/>
</bean>

<bean id="tobyUserDao" class="com.javabom.toby.chapter3.jdbc_템플릿_콜백_패턴.Chapter3UserDao">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="dataSourceUserDao" class="com.javabom.toby.user.dao.UserDao">
<property name="dataSource" ref="dataSource"/>
</bean>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.javabom.toby.chapter3.jdbc_템플릿_콜백_패턴;

import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.jupiter.api.DisplayName;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;

@SpringBootTest
@ContextConfiguration("/applicationContext.xml")
class TobyUserDaoTest {
Chapter3UserDao chapter3UserDao = new Chapter3UserDao();

@DisplayName("유저 저장테스트")
@Ignore
void add() {
/*
* 네거티브 테스트
* 예외상항에 대한 테스트
*/
chapter3UserDao.add(null);
chapter3UserDao.get("unknown");
}

}