问题描述
在赛车游戏中,赛车包括方程式赛车、场地越野赛车、运动汽车、卡车等类型,不同类型的赛车的车身、发动机、轮胎、变速箱等部件有所区别。玩家可以自行选择赛车类型,系统将根据玩家的选择创建出一辆完整的赛车。
结构图
编程实现
Car类
public class Car {
private String body;
private String engine;
private String tire;
private String gearbox;
public String getBody() {
return body;
}
public String getEngine() {
return engine;
}
public String getTire() {
return tire;
}
public String getGearbox() {
return gearbox;
}
public void setBody(String body) {
this.body = body;
}
public void setEngine(String engine) {
this.engine = engine;
}
public void setTire(String tire) {
this.tire = tire;
}
public void setGearbox(String gearbox) {
this.gearbox = gearbox;
}
}
抽象的Builder类
public abstract class Builder {
protected Car car = new Car();
public abstract void buildBody();
public abstract void buildEngine();
public abstract void buildTire();
public abstract void buildGearbox();
public Car getResult(){
return car;
}
}
具体的Builder类
public class F1Builder extends Builder{
@Override
public void buildBody() {
car.setBody("F1 body");
}
@Override
public void buildEngine() {
car.setEngine("F1 engine");
}
@Override
public void buildTire() {
car.setTire("F1 tire");
}
@Override
public void buildGearbox() {
car.setGearbox("F1 Gearbox");
}
}
public class RacingBuilder extends Builder{
@Override
public void buildBody() {
car.setBody("Racing body");
}
@Override
public void buildEngine() {
car.setEngine("Racing engine");
}
@Override
public void buildTire() {
car.setTire("Racing tire");
}
@Override
public void buildGearbox() {
car.setGearbox("Racing gearbox");
}
}
public class SportCarBuilder extends Builder{
@Override
public void buildBody() {
car.setBody("SportCar body");
}
@Override
public void buildEngine() {
car.setEngine("SportCar engine");
}
@Override
public void buildTire() {
car.setTire("SportCar tire");
}
@Override
public void buildGearbox() {
car.setGearbox("SportCar gearbox");
}
}
public class TruckBuilder extends Builder{
@Override
public void buildBody() {
car.setBody("Truck body");
}
@Override
public void buildEngine() {
car.setEngine("Truck engine");
}
@Override
public void buildTire() {
car.setTire("Truck tire");
}
@Override
public void buildGearbox() {
car.setGearbox("Truck gearbox");
}
}
Director类
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public Car construct(){
builder.buildBody();
builder.buildEngine();
builder.buildTire();
builder.buildGearbox();
return builder.getResult();
}
}
客户端类
public class Client {
public static void main(String[] args) {
Builder builder=new TruckBuilder();
Director director= new Director(builder);
Car car=director.construct();
System.out.println(car.getBody());
System.out.println(car.getEngine());
System.out.println(car.getTire());
System.out.println(car.getGearbox());
}
}