1、问题描述
小明家新开了一家自行车工厂,用于使用自行车配件(车架 frame 和车轮 tires )进行组装定制不同的自行车,包括山地车和公路车。
山地车使用的是Aluminum Frame(铝制车架)和 Knobby Tires(可抓地轮胎),公路车使用的是 Carbon Frame (碳车架)和 Slim Tries。
现在它收到了一笔订单,要求定制一批自行车,请你使用【建造者模式】告诉小明这笔订单需要使用那些自行车配置吧。
输入试例
3
mountain
road
mountain
2、建造者模式
可以分为产品、建造者、指导者
产品仅描述产品信息
建造者包含了建造产品各个部分的方式
指导者 指导 建造者以什么顺序 生成 产品的各个部分
3、代码
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
sc.nextLine();
for(int i=0;i<number;i++){
String s=sc.nextLine();
if(s.equals("mountain")){
Builder builder=new MountainBuilder();
Director director=new Director(builder);
director.Construct("Aluminum Frame","Knobby Tires");
Bike bike=builder.getResult();
bike.getProperties();
}else if(s.equals("road")){
Builder builder=new RoadBuilder();
Director director=new Director(builder);
director.Construct("Carbon Frame","Slim Tires");
Bike bike=builder.getResult();
bike.getProperties();
}
}
}
}
interface Bike{
void setFrame(String frame);
void setTires(String tires);
void getProperties();
}
class MountainBike implements Bike{
String frame;
String tires;
public void setFrame(String frame){
this.frame=frame;
}
public void setTires(String tires) {
this.tires = tires;
}
public void getProperties(){
System.out.println(this.frame+" "+this.tires);
}
}
class RoadBike implements Bike{
String frame;
String tires;
public void setFrame(String frame){
this.frame=frame;
}
public void setTires(String tires) {
this.tires = tires;
}
public void getProperties(){
System.out.println(this.frame+" "+this.tires);
}
}
interface Builder{
void buildFrame(String frame);
void buildTires(String tries);
Bike getResult();
}
class RoadBuilder implements Builder{
private RoadBike roadBike=new RoadBike();
@Override
public void buildFrame(String frame) {
roadBike.frame=frame;
}
@Override
public void buildTires(String tries) {
roadBike.tires=tries;
}
@Override
public Bike getResult() {
return roadBike;
}
}
class MountainBuilder implements Builder{
private MountainBike mountainBike=new MountainBike();
@Override
public void buildFrame(String frame) {
mountainBike.frame=frame;
}
@Override
public void buildTires(String tries) {
mountainBike.tires=tries;
}
@Override
public Bike getResult() {
return mountainBike;
}
}
class Director{
private Builder builder=null;
public Director(Builder builder){
this.builder=builder;
}
public void Construct(String frame,String tries){
builder.buildFrame(frame);
builder.buildTires(tries);
}
}