门面(Facade)模式:
该模式相当于提供了一个专门负责处理其它类的容器,和Mediator(中介者)模式有些类似。不同的是中介者模式是双向的,而门面模式是单向的。
这里只给出了《设计模式:java语言中的应用》书中代码,具体就不多描述,感觉这章没有《java与模式》中给出的示例更形象易懂。
maildata.txt文件:
hyuki@hyuki.com=Hiroshi Yuki
hanako@hyuki.com=Hanako Sato
tomura@hyuki.com=Tomura
mamoru@hyuki.com=Mamoru Takahashi
====================================================
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class Database {
private Database(){
//声明private以免new时会产生对象实例
}
public static Properties getProperties(String dbname){
//从数据库名称取得Properties
String filename = "src/my/yaner/facade/" +dbname + ".txt";
Properties prop = new Properties();
try {
prop.load(new FileInputStream(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
}
=========================================================================================
import java.io.IOException;
import java.io.Writer;
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>");
}
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();
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PageMaker {
private PageMaker(){
//因为不产生对象实例,故声明private
}
public static void makeWelcomPage(String mailaddr, String filename){
try {
Properties mailprop = Database.getProperties("maildata");
String username = mailprop.getProperty(mailaddr);
HtmlWriter writer = new HtmlWriter(new FileWriter(filename));
writer.title("Welcom to " + username + "'s page!");
writer.paragraph("欢迎来到" + username + "的网页。");
writer.paragraph("等你来信喔!");
writer.mailto(mailaddr, username);
writer.close();
System.out.println(filename + " is created for " + mailaddr +"("+ username + ")");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
PageMaker.makeWelcomPage("hyuki@hyuki.com", "welcome.html");
}
}