建造者模式 Builder
现在假设你想修一栋房子,房子的架构用二维数据来表示,如:0代表空间,1代表墙壁,2代表楼道。而你又想可以自己随意更换房子的材料,如一楼是砖墙做材料,二楼是石头做材料。
?
此时你可以找一个指挥者,他负责来读你的架构,再找两名能分别做砖墙和石头的建筑师来进行建造。现在只要指挥者按照你设计的架构去指挥不同建筑师来建造不同的模块,就能看到你所想要的房子。
/** * @author Jerval * @date 2011-4-25 */public interface IBuilder {public void createSpace();public void createWall();public void createPillar();public void nextFloor();}/** * @author Jerval * @date 2011-4-25 */public class StoneBuilder implements IBuilder {@Overridepublic void createSpace() {System.out.print("[]");}@Overridepublic void createWall() {System.out.print("█");}@Overridepublic void createPillar() {System.out.print("T");}@Overridepublic void nextFloor() {System.out.println();}}/** * @author Jerval * @date 2011-4-25 */public class BrickBuilder implements IBuilder {@Overridepublic void createSpace() {System.out.print(" ");}@Overridepublic void createWall() {System.out.print("|");}@Overridepublic void createPillar() {System.out.print("I");}@Overridepublic void nextFloor() {System.out.println();}}/** * @author Jerval * @date 2011-4-25 */public class Commander {private IBuilder builder;private int[][] design;public void setBuilder(IBuilder builder) {this.builder = builder;}public void setDesign(int[][] design) {this.design = design;}public void build() {for (int i = 0; i < design.length; i++) {for (int j = 0; j < design[i].length; j++) {switch (design[i][j]) {case 0:builder.createSpace();break;case 1:builder.createWall();break;case 2:builder.createPillar();break;default:System.out.println("the value:" + design[i][j]+ " is undefined!");break;}}builder.nextFloor();}}}/** * @author Jerval * @date 2011-4-25 */public class MainClass {public static void main(String[] args) {int design[][] = { { 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 0, 0, 0, 2, 1 },{ 1, 0, 1, 0, 1, 0, 1 }, { 1, 0, 2, 1, 0, 1, 1 },{ 1, 1, 0, 1, 0, 1, 1 }, { 1, 0, 0, 2, 0, 0, 1 },{ 1, 1, 1, 1, 1, 1, 1 } };Commander commander = new Commander();commander.setDesign(design);commander.setBuilder(new StoneBuilder());commander.build();System.out.println("=========================");commander.setBuilder(new BrickBuilder());commander.build();}}?
?