二十三种设计模式(四)建造者模式

建造者模式是指在使用复杂对象的过程中,将对象的创建和对象的行为进行分离,对象创建全权交给建造者(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;

}

}

由上可以看到,运用了建造者模式后,创建复杂对象变得灵活且可控。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值