또는 복사/붙여 넣기를 피하기 위해 template pattern을 사용하여 연결 배관을 추출 할 수 있습니다. 이제
abstract ConnectionTemplate {
private Connection connection = // ...
/**
* Method to be implementad by child classes
*/
public abstract void businessLogicCallback();
/**
* Template method that ensure that mandatory plumbing is executed
*/
public void doBusinessLogic() {
try {
openConnection();
// fetch single result, iterate across resultset, etc
businessLogicCallback();
finally {
closeConnection();
}
}
void openConnection() {
connection.open();
}
void closeConnection() {
if (connection != null) {
connection.close();
}
}
}
, 클래스를 구현하는
스프링 프레임 워크는이 기술을 사용하면
ImportantBusinessClass importantClass = new ImportantBusinessClass();
importantClass.doBusinessLogic(); // opens connection, execute callback and closes connection
처럼 사용 간단
class ImportantBusinessClass extends ConnectionTemplate {
@Override
public void businessLogicCallback() {
// do something important
}
}
로 할 수 있습니다 기본적인 아이디어는 뭔가처럼 어떤 곳에서는 특히 JdbcTemplate은 SQL, 연결, 행과 도메인 간의 매핑을 처리합니다. 개체 등 자세한 내용은 GitHub의 source code을 참조하십시오.
네, 주위에 조언을 할 수 있습니다. –
@MarkoTopolnik ok,하지만'Connection' 객체를 만들고 메소드의 다른 코드에 액세스 할 수 있도록해야합니다 (즉, 미래에'connection.setMethod (...) '와 같이하고 싶습니다). 것이 가능하다? – MyTitle
확실히 가능합니다. 질문은 당신이 좋아하는 것입니다. 하나의 아이디어는'ThreadLocal'을 사용하는 것입니다. –