builder模式是 builder负责产生组件, 然后使用director进行组装。
实现复杂对象的构建 与 它的表示进行分离。
比如迷宫的例子。
目的 是获取一个迷宫。
迷宫的组件是 room 和 wall (并且有的wall上面需要有door)
需要的原料
public class Maze { //迷宫
//interface 只能是 static final的成员变量 子类继承使用的时候无法改变父类的成员变量
// Maze 包含room的集合。
// private Room room;
private Map<String, Room> roomList = new HashMap<>();// 房间号和对应的Room
Room roomNo(int n){
return null;
}
public void addRoom(String no, Room room){
roomList.put(no, room);
}
public Room getRoom(String no){
return roomList.get(no);
}
Maze cloneMaze(){
return null;
}
public static final List<Room> mRoomList = new ArrayList<>();
@Override
public String toString() {
return "Maze{" +
"roomList=" + roomList.get("001").getSide("East") +
'}';
}
}
public interface DoorOrWall {
public boolean enter();//是否可以通过
}
public class Door implements DoorOrWall{
@Override
public boolean enter() {
return true;
}
}
public class Wall implements DoorOrWall{
//不可通过的墙壁
@Override
public boolean enter(){
return false;
}
}
然后 builder负责创建 room(添加wall) 和door(添加door)
public interface MazeBuilder <T>{
public T buildRoom(String room);
public T buildDoor(String roomFrom, String roomTo);
public Maze getMaze();
}
public class CountingMazeBuilder implements MazeBuilder<CountingMazeBuilder>{
Maze maze = null;
Room room = new Room();
int _rooms;
int _doors;
String[] direction = {"East", "West", "South", "North"};
public CountingMazeBuilder(){
_rooms = _doors = 0;
}
@Override
public CountingMazeBuilder buildRoom(String roomNum) {
room.setSide(direction[3], new Wall());
maze.addRoom(roomNum, room);
return this;
}
@Override
public CountingMazeBuilder buildDoor(String roomFrom, String roomTo) {
Room room1 = maze.getRoom(roomFrom);
Room room2 = maze.getRoom(roomTo);
Door door = new Door();
if(room1 != null){
System.out.println("room1 not null");
}
if(room1 == null){
System.out.println("room1 null");
}
room1.setSide("East", door);
return this;
}
@Override
public Maze getMaze() {
return maze;
}
//CountingMazeBuilder 自己的3个方法 而上面的是继承Builder的方法。
public CountingMazeBuilder buildMaze(){
//实例化 maze
this.maze = new Maze();
return this;
}
void addWall(int x, String[] direction){
}
void getCounts(int x, int y){}
}
director 导向或者组装器
public class Director {
private CountingMazeBuilder builder;
public Director(CountingMazeBuilder builder){
this.builder = builder;
}
public void construct(){
builder.buildMaze()
.buildRoom("001") //
.buildDoor("001", "002");
}
}
测试
public class MazeDriver {
public static void main(String[] args) {
CountingMazeBuilder builder = new CountingMazeBuilder();
Director director = new Director(builder);
director.construct();//给上面的builder 赋值(先实例化Maze,然后添加room)
Maze maze = builder.getMaze();
System.out.println(maze);
}
}
Director中一直持有 builder 在执行construct方法(给builder中字段Maze添加room) 进入Builder中 set值, 然后builder中字段Maze.addRoom()
然后就可以getMaze()获取迷宫了