建造者模式用于创建相对复杂,组成较多的对象。它包括几类角色:
类图关系如下:
代码如下:
package com.example; public class Table { private String head; private String content; private String footer; public String getHead() { return head; } public void setHead(String head) { this.head = head; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getTable(){ return this.head + "_" + this.content + "_" + this.footer; } }
public interface TableBuilder { public TableBuilder setTableHead(String head); public TableBuilder setTableContent(String content); public TableBuilder setTableFooter(String footer); public Table builder(); }
package com.example; public class TableBuilderImpl implements TableBuilder { private Table table; private static final String TYPE = "TYPE1"; public TableBuilderImpl(){ table = new Table(); } @Override public TableBuilder setTableHead(String head) { table.setHead(TYPE + head); return this; } @Override public TableBuilder setTableContent(String content) { table.setContent(TYPE + content); return this; } @Override public TableBuilder setTableFooter(String footer) { table.setFooter(TYPE + footer); return this; } @Override public Table builder() { return table; } }
public class Director { private TableBuilder builder; public Director(TableBuilder builder){ this.builder = builder; } public Table Builder(){ return builder.setTableHead("head") .setTableContent("content") .setTableFooter("footer") .builder(); } }
public class App { public static void main(String[] args) { Director direct = new Director(new TableBuilderImpl()); Table table = direct.Builder(); System.out.println(table.getTable()); } }
原文:http://www.cnblogs.com/Fredric-2013/p/4571573.html