当得到简单的对象的时候,使用工厂模式即可.
当得到复杂的对象,而且对象的一些属性需要繁琐配置的时候,使用建造者模式比较好.
这里以建造汽车为例,汽车的组件可以自由搭配.
package builder;
public class Car {
private String engine;
private String tire;
private String door;
private String seat;
public void setEngine(String engine) {
this.engine = engine;
}
public void setTire(String tire) {
this.tire = tire;
}
public void setDoor(String door) {
this.door = door;
}
public void setSeat(String seat) {
this.seat = seat;
}
@Override
public String toString() {
return Car [engine= + engine + , tire= + tire + , door= + door + , seat= + seat + ];
}
public void show() {
System.out.println(toString());
}
}
package builder;
public class CarBuilder {
private Car car = new Car();
public CarBuilder addEngine(String engine) {
car.setEngine(engine);
return this;
}
public CarBuilder addTire(String tire) {
car.setTire(tire);
return this;
}
public CarBuilder addDoor(String door) {
car.setDoor(door);
return this;
}
public CarBuilder addSeat(String seat) {
car.setSeat(seat);
return this;
}
/**
* 先设置好汽车的核心组件,然后再调用该方法
*/
public Car build() {
return car;
}
}
package builder;
import org.junit.Test;
public class CarTest {
@Test
public void test() {
Car car = new CarBuilder()//
.addDoor(华丽的车门)//
.addEngine(黄金的引擎)//
.addSeat(舒适的座椅)//
.addTire(耀眼的轮胎)//
.build();
car.show();
}
}
这样类似的builder在android用到的很多,在一些框架的配置对象中,也能看到建造者模式的影子.
|