Prepare a "window" for processing. As the program grows, more classes are created. To use those classes, understand the relationships between them and You need to call the methods in the correct order. In the Facade pattern, a "window" is prepared, and the user only has to make a request to the "window".
It will be a simple window for many other roles that make up the system. Providing a high-level and simple interface to the outside.
package facade;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PageMaker {
private PageMaker() {
}
public static void makeWelcomePage(String mailAddress, String fileName) {
try {
Properties mailProp = Database.getProperties("mailData");
String userName = mailProp.getProperty(mailAddress);
HtmlWriter writer = new HtmlWriter(new FileWriter(fileName));
writer.title("Welcome to " + userName + "'s page!");
writer.paragraph(userName + "Welcome to the page.");
writer.paragraph("I'm waiting for an email.");
writer.mailTo(mailAddress, userName);
writer.close();
System.out.println(fileName + " is created for " + mailAddress + " (" + userName + ")");
} catch (IOException e) {
e.printStackTrace();
}
}
}
I do each job, but I'm not aware of the role of Facade. He is called by the Facade role to do his job, but he does not call the Facade role from many other roles.
package facade;
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;
}
}
package facade;
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 mailAddress, String userName) throws IOException {
link("mailTo:" + mailAddress, userName);
}
public void close() throws IOException {
writer.write("</body>");
writer.write("</html>\n");
writer.close();
}
}
Roles that use the Facade pattern
package facade;
public class Main {
public static void main(String[] args) {
PageMaker.makeWelcomePage("[email protected]", "welcome.html");
}
}
https://github.com/aki0207/facade
I used this as a reference. Augmented and Revised Introduction to Design Patterns Learned in Java Language
Recommended Posts