应用场景:
相同的建造过程,不同的表现结果。根据传入的不同建造对象,返回不同的建造对象。
这里的例子是建造一辆奔驰和宝马。两者的建造过程是完全相同的,但是最后的表现是不同的
/**
* 建造的车
* @author Administrator
*
*/
public class Car {
public String name;
public String color;
@Override
public String toString() {
return "Car [name=" + name + ", color=" + color + "]";
}
}
------------------------------------------------------------------------------------------------------
/**
* 构建车的抽象过程,不同的车有相同的构建过程,但是最终的表现是不一样的
* @author Administrator
*
*/
public interface Builder {
public Car car = new Car();
//构建车的名字
public void buildName();
//构建车的颜色
public void buildColor();
//返回构建 的车
public Car getCar();
}
---------------------------------------------------------------------------------------------------------
/**
* 构建一辆宝马的建造对象
* @author Administrator
*
*/
public class BuildBaoMa implements Builder{
@Override
public void buildName() {
car.name = "宝马";
}
@Override
public void buildColor() {
car.color = "红色";
}
@Override
public Car getCar() {
return car;
}
}
-----------------------------------------------------------------------------------------------
/**
* 构建一辆奔驰的建造对象
* @author Administrator
*
*/
public class BuildBenChi implements Builder{
@Override
public void buildName() {
car.name ="奔驰";
}
@Override
public void buildColor() {
car.color = "银灰色";
}
@Override
public Car getCar() {
return car;
}
}
--------------------------------------------------------------------------------------------------
/**
* 建造者,传入具体的构建对象,返回一个构建的车辆
* @author Administrator
*
*/
public class Director {
private Builder builder;
public Director(Builder builder) {
super();
this.builder = builder;
}
public void setBuilder(Builder builder) {
this.builder = builder;
}
public void build(){
builder.buildName();
builder.buildColor();
}
public Car getCar(){
return builder.getCar();
}
}
---------------------------------------------------------------------------------------------
public class Test {
/**测试类
* @param args
*/
public static void main(String[] args) {
//建造一辆宝马
Director director = new Director(new BuildBaoMa());
director.build();
System.out.println(director.getCar());
//建造一辆奔驰
director.setBuilder(new BuildBenChi());
director.build();
System.out.println(director.getCar());
}
}