目录

案例一 

案例二




使用场景:当构建一个复杂的对象需要传入很多参数的时候,或者是一个对象的属性有很多,但是使用时也许只需要这个对象的几个属性,如果使用构造器的话,就得将不需要的参数也传个null进去,比方说一个对象有100个属性,但是我只需要里面的2个属性,那我得new对象时传98个null进去,这两种情况下就可以选择使用建造者模式。 


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;
}
}


 接口

每个方法的返回值都是TerrainBuilder对象,就可以实现链式编程。


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 Main {
public static void main(String[] args) {
TerrainBuilder builder = new ComplexTerrainBuilder();
Terrain t = builder.buildFort().buildMine().buildWall().build();
}
}

案例二


Person类,假设有100个参数 


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;
}
}


测试


public class Main {
public static void main(String[] args) {
Person p = new Person.PersonBuilder()
.basicInfo(1, "zhangsan", 18)
//.score(20)
.weight(200)
//.loc("bj", "23")
.build();
}
}