365日アプリケーションブログ

一日一アプリケーションを構築することを目指すブログです。アプリケーションの種類は基本的に気まぐれです。

【20140418】【Java】Singletonパターンを使う

お題

Singletonパターンを使う

プログラム概要

Singletonクラスにmain.jspに最初にアクセスした時間を保持しておく。

その後、elapesedtime.jspにアクセスするとSingletonクラス内の時間と

現在の時間の差を計算し画面に表示させる

ソース

GetDate.java(Singletonクラス)

package jp;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;

public class GetDate {
	private static Date date;

	private static GetDate fileDate = new GetDate();
	private GetDate(){
		date = new Date();
		System.out.println("コンストラクタが呼ばれました");
	}
	
	public static GetDate getInstance() {
		return fileDate;
	}
	public Date getDateTime() {
		return date;
	}
}

main.jsp

<%@page import="jp.GetDate"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>日付取得</title>
</head>
<body>
<% GetDate gd = GetDate.getInstance(); %>
<span>起動時の日時は<%= gd.getDateTime().toString() %>です</span>
</body>
</html>

elapsedtime.jsp


<%@page import="java.util.Date"%>
<%@page import="jp.GetDate"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>日付取得</title>
</head>
<body>
<% GetDate gd = GetDate.getInstance(); %>
<% Date currentDate = new Date(); %>
<span>起動からの経過時間は<%= (currentDate.getTime() - gd.getDateTime().getTime())/1000 %>秒です</span>
</body>
</html>

実行結果

main.jsp

f:id:mocomei:20140419232026p:plain

elapesedtime.jsp

f:id:mocomei:20140419232046p:plain