デザインパターン Facade:シンプルな窓口

概要

複雑な処理に対して、最小限のAPI(公開メソッド)のみを提供する

クラス図


本例

※下線=static

システム

Facade(正面)
public class PageMaker {
 複雑な部品の複雑な使用方法をまとめる
 public static void makeWelcomePage(String mailaddr, String filename) {
  Properties mailprop = Database.getProperties(“maildata”);
  String username = mailprop.getProperty(mailaddr);
  try {
   HtmlWriter writer = new HtmlWriter(new FileWriter(filename));
   writer.title(“Welcome to ” + username + “‘s page!”);
   writer.paragraph(username + “のページへようこそ。”);
   writer.paragraph(“社員募集中”);
   writer.mailto(mailaddr, username);
   writer.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

その他複雑な部品
public class HtmlWriter {
 private Writer writer;

 public HtmlWriter(Writer writer) {
  this.writer = writer;
 }

 public void title(String title) throws IOException {
  this.writer.write(“<html>\n”);
  this.writer.write(“<head><title>” + title + ”</title></head>\n”);
  this.writer.write(“<body>\n”);
  this.writer.write(“<h1>” + title + “</h1>\n”);
 }

 public void paragraph(String msg) throws IOException {
  this.writer.write(“<p>” + msg + “</p>”);
 }

 public void link(String href, String caption) throws IOException {
  this.paragraph(“<a href=\”” + href + ”\”>” + caption + “</a>”);
 }

 public void mailto(String mailaddr, String username) throws IOException {
  this.link(“mailto:” + mailaddr, username);
 }

 public void close() throws IOException {
  this.writer.write(“</body>\n”);
  this.writer.write(“</html>\n”);
  this.writer.close();
 }
}


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) {
   e.printStackTrace();
  }
  return prop;
 }
}

Client(利用者)

public class Main {
 public static void main(String[] args) {
  利用者は複雑なシステムに対してこのメソッドしか使用していない
  PageMaker.makeWelcomePage(“yone@office-yone.com”, “welcome.html”);
 }
}