Singleton의 사용 이유는 간단합니다. 서로 다른 페이지에서 동일한 객체를 사용하기 위해 단일 객체로 생성하여 제한하는 것이 목적입니다.Java의 문법에서 변수 선언 시 static을 걸어주는 것처럼 말이죠
public class Velog1 {
@Override
public String toString() {
return super.toString();
}
}
<!-- 기존의 객체 생성 방식(생성된 객체가 전부 다른 값과 주소를 가짐 --!>
<fieldset>
<% Velog1 ob1 = new Velog1(); %>
<c:set var="ob2" value="<%=new Velog1() %>" />
<jsp:useBean id="ob3" class="ex01.Velog1" />
<ul>
<li>ob1 : <%=ob1 %></li>
<li>ob2 : ${ob2 }</li>
<li>ob3 : ${ob3 }</li>
</ul>
</fieldset>
<※ 결과는 다음과 같습니다.>
public class VelogDAO {
private Connection conn;
private Statement stmt;
private ResultSet rs;
private Context init;
private DataSource ds;
public VelogDAO() throws NamingException {
init = new InitialContext();
ds = (DataSource) init.lookup("java:comp/env/jdbc/oracle");
}
// DB 버전 반환
public String getVersion() throws SQLException {
String version = null;
String sql = "select banner from v$version";
// DataSource : 여러개의 connection을 가지고 있다가 요청받으면 하나씩 내어줌
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
version = rs.getString("banner");
}
rs.close();
stmt.close();
conn.close();
return version;
}
}
public class Velog2 {
// 클래스의 객체를 저장할 필드
private static Velog2 instance;
// 만들어진 단일 객체를 반환하는 static 메서드
public static Velog2 getInstance() {
if (instance == null) {
// 내부에서는 자유롭게 생성자 호출 가능
instance = new Velog2();
}
// 만약 객체가 만들어져있다면, 기존 객체를 반환하고
return instance;
// 객체가 없다면 한번만 새로 생성하여 객체를 반환한다
}
private Velog2() {
// 외부에서는 기본 생성자를 호출할 수 없다
// <jsp:useBean> 으로 객체를 생성할 수 없다
}
@Override
public String toString() {
return super.toString() + " (싱글톤 객체)";
}
}
<%@ include file="ex01-directive.jsp" %>
<jsp:include page="ex01-actionTag.jsp" />
<h3>동일한 페이지 동일한 객체</h3>
<fieldset>
<%
Velog2 ob4 = Velog2.getInstance();
%>
<c:set var="ob5" value="${Velog2.getInstance() }" />
<ul>
<li>ob4 : <%=ob4%></li>
<li>ob5 : ${ob5 }</li>
</ul>
</fieldset>
<br>
<%@ page import="ex01.Velog2" %>
<h3>ex01-directive.jsp</h3>
<%
Velog2 ob6 = Velog2.getInstance();
%>
<h3>다른 페이지 동일한 객체</h3>
<fieldset>
<legend>ex01-directive.jsp</legend>
<ul>
<li>ob6 : <%=ob6 %></li>
</ul>
</fieldset>
<%@ page import="ex01.Velog2" %>
<h3>ex01-actionTag.jsp</h3>
<%
Velog2 ob7 = Velog2.getInstance();
%>
<h3>다른 페이지 동일한 객체</h3>
<fieldset>
<legend>ex01-actionTag.jsp</legend>
<ul>
<li>ob7 : <%=ob7 %></li>
</ul>
</fieldset>
<※ 싱글톤 객체 생성 결과는 다음과 같습니다.>
ConnectionPool은 하나의 객체에 DB에 여러개의 Connection객체를 생성하지 않고 하나의 객체에 여러개의 Thread를 연결시켜 효율을 극대화 시키는 방식입니다.