1、建造者模式
(1)概念
将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示。建造者模式注重组装过程,而工厂方法模式更注重创建过程
2、建造者模式的实现
(1)UML
(2)实现
- 抽象建造者
public interface TerrainBuilder { TerrainBuilder buildWall(); TerrainBuilder buildFort(); TerrainBuilder buildMine(); Terrain build(); }
- 具体建造者
public class ComplexTerrainBuilder implements TerrainBuilder { Terrain terrain = new Terrain(); @Override public TerrainBuilder buildWall() { terrain.w = new Wall(10, 10, 50, 50); return this; } @Override public TerrainBuilder buildFort() { terrain.f = new Fort(10, 10, 50, 50); return this; } @Override public TerrainBuilder buildMine() { terrain.m = new Mine(10, 10, 50, 50); return this; } @Override public Terrain build() { return terrain; } }
- 被建造对象
public class Terrain { Wall w; Fort f; Mine m; } class Wall { int x, y, w, h; public Wall(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } } class Fort { int x, y, w, h; public Fort(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } } class Mine { int x, y, w, h; public Mine(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } }
它是包含多个组成部件的复杂对象,由具体建造者来创建其各个零部件
- 指挥者
调用建造者对象中的部件构造与装配方法完成复杂对象的创建,在指挥者中不涉及具体产品的信息
TerrainBuilder builder = new ComplexTerrainBuilder(); Terrain t = builder.buildFort().buildMine().buildWall().build();
3、在JDK中的运用
StringBulider的append方法