デザインパターンを究める Facadeパターン
Databaseクラス(Database.java)
package pagemaker;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
Public class Database{
private Database(){ //newでインスタンスを生成させないprivate宣言
}
//↓データベース名からPropertiesを得る
public static Properties getProperties(String dbname) {
String filename = dbname + ".txt";
Properties prop = new Properties();
try {
prop.load(new FileInputStream(filename));
}catch (IOExcepion e) {
System.out.println("Warning:"+filename+" is not found.");
}
return prop;
}//getProperties
}//class
データファイル(maildata.txt)
sample@s1.com = Sam Ple
sample2@g1.com = AM Le
sample3@g3.com = BE Po
sample4@g4.com = Tanaka
HtmlWriterクラス(HtmlWriter.java)
package pagemaker;
import java.io.Writer;
import java.io.IOException;
public class HtmlWriter{
private Writer writer;
public HtmlWriter(Writer writer){ //コンストラクタ
this.writer = writer;
}
public void title(String title) throws IOException{ //タイトルの出力
writer.write("<html>");
writer.write("<head>");
writer.write("<title>" + title + "</title>");
writer.write("</head>");
writer.write("<body>\n");
writer.write("<h1>" + title + "<h1>\n");
}
public void paragraph(String msg) throws IOException{ //段落の出力
writer.write("<p>" + msg + "</p>\n");
}
public void link(String href , String caption) throws IOException{//リンク出力
paragraph(" <a href=\" " + href + " \"> " + caption +"</a>");
} // link
public void mailto(String mailaddr, String username) throws IOException{
link("mailto;" + mailaddr, username);
}
public void close() throws IOException{
writer.write("</body>");
writer.write("</html>\n");
writer.close();
}
} //class
PageMakerクラス(PageMaker.java)
package pagemaker;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PageMaker {
private PageMaker() {
}
public static void makeWelcomePage(String mailaddr,String filename){
try{
Properties mailprop = Database.getProperties("maildata");
String username = mailprop.getProperty(mailaddr);
HtmlWriter writer = new HtmlWriter(new FileWriter(filename));
writer.title("Welcome to" + username +" 's page!");
writer.paragraph(username + "のページへようこそ。 ");
writer.paragraph(username + "へのメール待ってますね。");
writer.mailto(mailaddr,username);
writer.close();
System.out.println(filename + "is created for " + mailaddr +"("+ username +")" );
}catch(IOException e){
e.printStackTrace();
}
}
}
Mainクラス (Main.java)
import pagemaker.PageMaker;
public class Main{
public static void main(String[] args){
PageMaker.makeWelcomePage("sample@s1.com","welcome.html");
}
}