Java设计模式之Builder模式
什么是builder?
将单个简单对象组装成为复杂对象的过程
有什么好处?
builer并不知道子类是如何实现的,但是它能够其他的子类完美的替换。正是因为不知道才能够替换, 正是因为可以替换, 组件才具有高价值。
类说明
类名 | 类说明 |
---|---|
Builder | 定义了决定文档结构的抽象类(这不就是模板方法吗) |
Director | 编写一个文档的类(这不就是抽象工厂吗) |
TextBuilder 类 | 使用纯文本( 普通字符串 )编写文档 |
HTMLBuilder 类 | 使用HTML 编写文档 |
代码
Builder
public abstract class Builder {
public abstract void makeTitle(String title);
public abstract void makeString(String str);
public abstract void makeitems(String[] items ) ;
public abstract void close();
}
Director
public class Director {
private Builder builder; //这里使用的是委托的实现方式
public Director(Builder builder) {
this.builder = builder;
}
public void construct() { //编写文档
builder.makeTitle("Greeting"); //标题
builder.makeString(" 从早上至下午 "); //字符串
builder.makeitems(new String[] { "早上好。", "下午好", }); //条目
builder.makeString(" 晚 上 ");
builder.makeitems(new String[] { "晚上好。", "晚安。", "再见。", });
builder.close();
}
}
TextBuilder
public class TextBuilder extends Builder {
private StringBuffer buffer = new StringBuffer();
public void makeTitle(String title) {
buffer.append ( " ======= ======================= \n " ) ;
buffer.append ( "「 "+title+"」 \n " );
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 void close() {
buffer.append(" ================ ============== \n ");
}
public String getResult() {
return buffer.toString();
}
}
HTMLBuilder
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public 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(" <h t ml ><he a d ><t i t l e >" + title + " </ t i t l e ></ he a d ><body> ");
writer.println(" <hl >" + title + "</hl>");
}
public void makeString(String str) {
writer.println(" <p>" + str + "</p>");
}
public void makeitems(String[] items) {
writer.println(" <ul >");
for (int i = 0; i < items.length; i++) {
writer.println(" <li>" + items[i] + "</ l i >");
writer.println(" </ ul >");
}
}
public void close() {
writer.println(" </ bod y></ ht ml >");
writer.close();
}
public String getResult() {
return filename;
}
}
TestCase
public class TestCase {
public static void main(String[] args) {
TextBuilder tb = new TextBuilder();
Director d = new Director(tb);
d.construct();
String result = tb.getResult();
System.out.println(result);
HTMLBuilder htb = new HTMLBuilder();
Director d2 = new Director(htb);
d2.construct();
String result2 = htb.getResult();
System.out.println(result2);
}
}
运行结果