建造者模式是指在使用复杂对象的过程中,将对象的创建和对象的行为进行分离,对象创建全权交给建造者(Builder)完成。
案例如下:
/**
* 海
* */
public class Sea {
int x;
int y;
}
/**
* 商店
* */
public class Shop {
int x;
int y;
}
/**
* 塔
* */
public class Tower {
int x;
int y;
}
/**
* 墙
* */
public class Wall {
int x;
int y;
}
/**
* 游戏地图
* */
public class Map {
//防御塔
ArrayList<Tower> tower;
//墙
ArrayList<Wall> wall;
//海
ArrayList<Sea> sea;
//商店
Shop shop;
public Map(ArrayList<Tower> tower,ArrayList<Wall> wall,ArrayList<Sea> sea,Shop shop){
this.sea = sea;
this.wall = wall;
this.tower = tower;
this.shop =shop;
}
}
这是一张简单的游戏地图。但实际创建的时候,为了保持游戏地图的多样性。传进来的Entity多种多样且有可能没有海或者没有墙。而且还有可能存在先后的问题比如说必须有海的地图才能有塔等
此时就需要一个专门用来为Map创建的对象的Builder出现。
/**
* 建造者
* */
public interface Builder {
//创建带墙的Builder
public Builder getWallBuilder(ArrayList<Wall> wall);
//创建带海的Builder
public Builder getSeaBuilder(ArrayList<Sea> sea);
//创建带塔的Builder
public Builder getTowerBuilder(ArrayList<Tower> tower);
//创建带商店的Builder
public Builder getShopBuilder(Shop shop);
//返回地图对象
public Map bulid();
}
public class MapBuilder implements Builder{
Map map;
@Override
public Builder getWallBuilder(ArrayList<Wall> wall) {
map.setWall(wall);
return this;
}
@Override
public Builder getSeaBuilder(ArrayList<Sea> sea) {
map.setSea(sea);
return this;
}
@Override
public Builder getTowerBuilder(ArrayList<Tower> tower) {
//必须有海才能有塔
if(this.map.sea==null) throw new RuntimeException("建塔失败,此时没有海");
map.setTower(tower);
return this;
}
@Override
public Builder getShopBuilder(Shop shop) {
map.setShop(shop);
return this;
}
@Override
public Map bulid() {
return map;
}
}
此时地图类不再需要自己创建对象
public class Map {
//防御塔
ArrayList<Tower> tower;
//墙
ArrayList<Wall> wall;
//海
ArrayList<Sea> sea;
//商店
Shop shop;
private Map(){
}
public void setTower(ArrayList<Tower> tower) {
this.tower = tower;
}
public void setWall(ArrayList<Wall> wall) {
this.wall = wall;
}
public void setSea(ArrayList<Sea> sea) {
this.sea = sea;
}
public void setShop(Shop shop) {
this.shop = shop;
}
}
由上可以看到,运用了建造者模式后,创建复杂对象变得灵活且可控。