分类: Java
2009-04-01 18:48:25
public class MazeDirector {
private int[][] maze;
private IMazeBuilder mazeBuilder;
public void setMaze(int[][] maze) {
this.maze = maze;
}
public void setMazeBuilder(IMazeBuilder mazeBuilder) {
this.mazeBuilder = mazeBuilder;
}
public void buildMaze() {
for(int i = 0; i < maze.length; i++) {
for(int j = 0; j < maze[i].length; j++) {
// 由于mazeBuilder是IMazeBuilder型态
// 所以无论Builder实例为何,这边的程式都无需变动
switch (maze[i][j]) {
case 0:
mazeBuilder.createRoadBlock();
break;
case 1:
mazeBuilder.createWallBlock();
break;
case 2:
mazeBuilder.createTreasureBlock();
break;
default:
System.out.println("undefined");
}
}
mazeBuilder.nextRow();
}
}
}
public interface IMazeBuilder {
public void createRoadBlock();
public void createWallBlock();
public void createTreasureBlock();
public void nextRow();
}
public class SolidMazeBuilder implements IMazeBuilder {
public void createWallBlock() {
System.out.print("█");
}
public void createRoadBlock() {
System.out.print(" ");
}
public void createTreasureBlock() {
System.out.print("$ ");
}
public void nextRow() {
System.out.println();
}
}
public class DiamondMazeBuilder implements IMazeBuilder {
public void createWallBlock() {
System.out.print("◇");
}
public void createRoadBlock() {
System.out.print(" ");
}
public void createTreasureBlock() {
System.out.print("* ");
}
public void nextRow() {
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
int[][] maze = {{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}};
MazeDirector mazeDirector = new MazeDirector();
mazeDirector.setMaze(maze);
System.out.println("Build SolidMaze....");
mazeDirector.setMazeBuilder(new SolidMazeBuilder());
mazeDirector.buildMaze();
System.out.println("Build DiamondMaze....");
mazeDirector.setMazeBuilder(
new DiamondMazeBuilder());
mazeDirector.buildMaze();
}
}