/** * 声明产生“文件”的所有方法的抽象类。 * * @author Administrator * */ public 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(); //取得完成文件的方法 }
public class Director { private Builder builder; /** * 传入Builder 的子类对象 * @param builder */ public Director(Builder builder) { this.builder = builder; } /** * 建立 文件 * @return */ public Object construct(){ builder.makeTitle("terry"); builder.makeString("android developer"); builder.makeItems(new String[]{"Framework","java","native","HAL","Service"}); builder.makeString("windows phone 7 developer"); builder.makeItems(new String[]{"for silverlight","XNA"}); return builder.getResult(); } }
public class TextBuilder extends Builder{
private StringBuffer buffer=new StringBuffer();
@Override
public Object getResult() {
// TODO Auto-generated method stub
buffer.append("======================\n");
return buffer.toString();
}
@Override
public void makeItems(String[] items) {
// TODO Auto-generated method stub
for(String str:items)
{
buffer.append(str+"\n");
}
}
@Override
public void makeString(String str) {
// TODO Auto-generated method stub
buffer.append(str+"\n");
}
@Override
public void makeTitle(String title) {
// TODO Auto-generated method stub
buffer.append("=========================\n");
buffer.append(title+"\n");
}
}
public class HtmlBuilder extends Builder{
private String fileName;
private StringBuffer writer=new StringBuffer();
@Override
public Object getResult() {
// TODO Auto-generated method stub
writer.append("");
return writer.toString();
}
@Override
public void makeItems(String[] items) {
// TODO Auto-generated method stub
writer.append("
<ul>");
for(String str:items){
writer.append("
<li>"+str+"</li>
");
}
writer.append("</ul>
");
}
@Override
public void makeString(String str) {
// TODO Auto-generated method stub
writer.append("
"+str+"
");
}
@Override
public void makeTitle(String title) {
// TODO Auto-generated method stub
fileName=title+".html";
writer.append(fileName);
writer.append(""+title+"");
writer.append("
<h1>"+title+"</h1>
");
}
}