- 构建复杂对象
- 分离复杂对象的构建和表示
- 同样的构建过程可以创建不同的表示(Simple和Complex)
- 无需记忆,自然使用(面向对象的思想)
- 与模板方法非常像,模板方法强调的是方法执行,而构建器强调的是对象构建(创建)
- 构建器模式与工厂模式的区别
UML类图
实现
- 先要有一个初始化对象
- 再一步一步地去构建里面的成员属性
- 最后返回构建完毕的对象
- 链式编程(编程简单),builder经常和这种编程方式一起用
- 将Builder作为所构建类的内部静态类并将构造方法设为private—->别人new不了Person,只能通过内部静态类来构建Person,相当于是静态工厂
- 可以指定对象的某一个部分,用不到的用不着每次都传
- 最后的build();拿到最终定制的对象
地形类
``` package com.mashibing.dp.builder;
// 地形 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;
}
}
<a name="DEwjK"></a>
### 构建器接口
package com.mashibing.dp.builder;
public interface TerrainBuilder { TerrainBuilder buildWall(); TerrainBuilder buildFort(); TerrainBuilder buildMine(); Terrain build(); }
<a name="wiKH8"></a>
### 复杂构建器实现
package com.mashibing.dp.builder;
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;
}
}
<a name="shfZg"></a>
### 构建器作为静态内部类
- 没有接口只有类
- 没有多种多样的实现类(即只有一种方式的构建器)
package com.mashibing.dp.builder;
public class Person { int id; String name; int age; double weight; int score; Location loc;
private Person() {}
public static class PersonBuilder {
Person p = new Person();
public PersonBuilder basicInfo(int id, String name, int age) {
p.id = id;
p.name = name;
p.age = age;
return this;
}
public PersonBuilder weight(double weight) {
p.weight = weight;
return this;
}
public PersonBuilder score(int score) {
p.score = score;
return this;
}
public PersonBuilder loc(String street, String roomNo) {
p.loc = new Location(street, roomNo);
return this;
}
public Person build() {
return p;
}
}
}
class Location { String street; String roomNo;
public Location(String street, String roomNo) {
this.street = street;
this.roomNo = roomNo;
}
}
<a name="vO7Go"></a>
### 使用
package com.mashibing.dp.builder;
public class Main { public static void main(String[] args) { TerrainBuilder builder = new ComplexTerrainBuilder(); Terrain t = builder.buildFort().buildMine().buildWall().build(); //new Terrain(Wall w, Fort f, Mine m) //Effective Java
Person p = new Person.PersonBuilder()
.basicInfo(1, "zhangsan", 18)
//.score(20)
.weight(200)
//.loc("bj", "23")
.build();
}
} ```
有必要吗?为什么不用带参的构造方法?
- 可以用带参的构造方法,没问题,都可以实现
- 但是用这个模式主要是针对参数非常多的时候
- 《Effective Java》构建复杂对象建议用构建器模式
随想
- 静态内部类可以访问外部类的私有成员方法和变量
- 静态内部类初始化的方法、嵌套类的初始化方法