【图解设计模式】Facade模式

可以为系统提供一个简单窗口。

示例

编写简单的Web页面。

类图

mwJ8yD.png

Database类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package pagemaker;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class Database {
private Database() {}

public static Properties getProperties(String dbname) {
String filename = dbname + ".txt";
Properties prop = new Properties();

try {
prop.load(new FileInputStream(filename));
} catch (IOException e) {
System.out.println("Warning: " + filename + " is not found.");
}

return prop;
}
}

HtmlWriter类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package pagemaker;

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();
}
}

PageMaker类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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("./xxx/maildata");
String username = mailprop.getProperty(mailaddr);
HtmlWriter writer = new HtmlWriter(new FileWriter(filename));
writer.title("Welcome to " + username + "'s page!");
writer.paragraph(username + "欢迎来到" + username + "的主页。");
writer.paragraph("等着你的邮件哦!");
writer.mailto(mailaddr, username);
writer.close();
System.out.println(filename + " is created for " + mailaddr + " (" + username + ")");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Main类

1
2
3
4
5
6
7
8
import pagemaker.PageMaker;

public class Main {

public static void main(String[] args) {
PageMaker.makeWelcomePage("hyuki@hyuki.com", "welcome.html");
}
}

运行结果

1
welcome.html is created for hyuki@hyuki.com (Hiroshi Yuki)

m048fI.png

登场角色

Facade(窗口)

Facade角色是代表构成系统的许多其他角色的“简单窗口”。Facade角色向系统外部提供高层接口(API)。在示例程序中,由PageMaker类扮演此角色。

构成系统的许多其他角色

这些角色各自完成自己的工作,它们并不知道Facade角色。Facade角色调用其他角色进行工作,但是其他角色不会调用Facade角色。在示例程序中,由Database类和HtmlWriter类扮演此角色。

Client(请求者)

Client角色负责调用Facade角色。在示例程序中,由Main类扮演此角色。

类图

m05e4s.png