#format java /** * BuilderPattern Example */ import java.io.*; abstract class Builder { public abstract void makeTitle(String title); public abstract void makeString(String str); public abstract void makeItems(String[] items); public abstract Object getResult(); } class Director { private Builder builder; public Director(Builder builder) { this.builder = builder; } public Object construct() { builder.makeTitle("Greeting"); builder.makeString("In the morning and afternoon..."); builder.makeItems(new String[] { "Good morning", "Good afternoon", }); builder.makeString("In the evening..."); builder.makeItems(new String[] { "Hello", "Good evening", "Good nignt", }); return builder.getResult(); } } class TextBuilder extends Builder { private StringBuffer buffer = new StringBuffer(); public void makeTitle(String title) { buffer.append("=====================\n"); buffer.append("["+title+"]"); buffer.append("\n"); } public void makeString(String str) { buffer.append(" * "+str+"\n"); buffer.append("\n"); } public void makeItems(String[] items) { for(int i=0; i < items.length; i++) { buffer.append(" . "+items[i]+"\n"); } buffer.append("\n"); } public Object getResult() { buffer.append("=======================\n"); return buffer.toString(); } } class HTMLBuilder extends Builder { private String filename; private PrintWriter writer; public void makeTitle(String title) { filename = title+".html"; try { writer = new PrintWriter(new FileWriter(filename)); } catch(IOException e) { e.printStackTrace(); } writer.println(""+title+""); writer.println("

"+title+"

"); } public void makeString(String str) { writer.println("

"+str+"

"); } public void makeItems(String[] items) { writer.println(""); } public Object getResult() { writer.println(""); writer.close(); return filename; } } public class BuilderDoc { public static void main(String[] args) { Director d1 = new Director(new TextBuilder()); String result = (String)d1.construct(); System.out.println(result); Director d2 = new Director(new HTMLBuilder()); String filename = (String)d2.construct(); System.out.println(filename); } }