创建迷宫 - 生成器模式
如果您有个物件必须建立,物件是由个别组件(Component)组合而成,个别组件建立非常复杂,但说明如何运用组件建立非 常简单,您希望将建立复杂组件与运用组件方式分离,则可以使用Builder模式。
举例来说,您想要建立一个迷宫产生程序,迷宫使用二维阵列来定义,0表示道路,1表示墙,2表示宝物,根据所定义的二维迷宫阵列,您想要程序自动产生各种不 同材质的迷宫,例如砖墙迷宫,钻石迷宫等。在不同的绘图引擎下,建立各种材质非常复杂,但建立迷宫的表达方式很简单,象是这边要道墙,那边要条路,旁边要 放个宝藏之类的。
这时候可以使用建造者模式(Builder)
UML图:
目录结构:
代码:
package design_mode.builder; /** * Created by Andrew on 2016/11/7. */ public interface Maze { void paint(); }
package design_mode.builder; /** * Created by Andrew on 2016/11/7. */ public abstract class MazeBuilder { char [][] maze; MazeBuilder(char [][] maze){this.maze = maze;} public void buildWall(int i, int j){} public void buildRoom(int i, int j){} public void buildTreasure(int i, int j){} public abstract Maze getMaze(); }
package design_mode.builder; /** * Created by Andrew on 2016/11/7. */ public class MazeDirector { char [][] maze; MazeBuilder builder; MazeDirector(char [][] maze, MazeBuilder builder){ this.maze = maze; this.builder = builder; } public Maze construct(){ for (int i = 0; i < maze.length; i++) { for (int j = 0; j < maze[i].length; j++) { switch (maze[i][j]){ case 0: builder.buildWall(i,j); break; case 1: builder.buildRoom(i, j); break; case 2: builder.buildTreasure(i,j); break; } } } return builder.getMaze(); } public static void main(String[] args) { char[][] maze = new char[][]{ {0,1,0,1,0}, {0,1,2,1,0}, {0,1,0,1,0} }; // MazeDirector mazeDirector = new MazeDirector(maze,new PlainMazeBuilder(maze)); MazeDirector mazeDirector = new MazeDirector(maze,new CountMazeBuilder(maze)); Maze maze1= mazeDirector.construct(); maze1.paint(); } }
package design_mode.builder; /** * Created by Andrew on 2016/11/7. */ public class PlainMazeBuilder extends MazeBuilder { PlainMazeBuilder(char[][] maze) { super(maze); } @Override public void buildRoom(int i, int j) { maze[i][j] = '|'; } @Override public void buildWall(int i, int j) { maze[i][j] = '□'; } @Override public void buildTreasure(int i, int j) { maze[i][j] = '※'; } @Override public Maze getMaze() { return new Maze() { @Override public void paint() { for (char[] row : maze){ for (char ele : row){ System.out.print(ele); } System.out.println(); } } }; } }
package design_mode.builder; /** * Created by Andrew on 2016/11/7. */ public class CountMazeBuilder extends MazeBuilder { int i; int j; int k; CountMazeBuilder(char[][] maze) { super(maze); } @Override public void buildTreasure(int i, int j) { this.i++; } @Override public void buildWall(int i, int j) { this.j++; } @Override public void buildRoom(int i, int j) { this.k++; } @Override public Maze getMaze() { return new Maze() { @Override public void paint() { System.out.println("当前迷宫物件:"); System.out.println("宝藏:"+i+"个"); System.out.println("墙壁:"+j+"面"); System.out.println("房间:"+k+"个"); } }; } }