写一段Java代码 ConcreteBulilder类中的三个方法:buildPartA、buildPartB、buildPartC分别调用product的setPartX(X代表A、B、C) yiwen 2023/5/16 19:11:56 Director类中,包含构造函数与setBuilder(参数)方法 yiwen 2023/5/16 19:16:30 主类定义为Client,主要代码有: Builder builder=new ConcreteBuilder(); Director director=new Director(builder); Product product=director.construct(); 然后最后可以调用product的getXXX方法,并输出相关属性值;
时间: 2023-07-15 09:13:02 浏览: 113
下面是Java代码实现:
```java
public interface Builder {
void buildPartA();
void buildPartB();
void buildPartC();
Product getProduct();
}
public class ConcreteBuilder implements Builder{
private Product product;
public ConcreteBuilder() {
this.product = new Product();
}
@Override
public void buildPartA() {
product.setPartA("Part A");
}
@Override
public void buildPartB() {
product.setPartB("Part B");
}
@Override
public void buildPartC() {
product.setPartC("Part C");
}
@Override
public Product getProduct() {
return product;
}
}
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void setBuilder(Builder builder) {
this.builder = builder;
}
public Product construct() {
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
return builder.getProduct();
}
}
public class Client {
public static void main(String[] args) {
Builder builder = new ConcreteBuilder();
Director director = new Director(builder);
Product product = director.construct();
System.out.println("Part A: " + product.getPartA());
System.out.println("Part B: " + product.getPartB());
System.out.println("Part C: " + product.getPartC());
}
}
public class Product {
private String partA;
private String partB;
private String partC;
public String getPartA() {
return partA;
}
public void setPartA(String partA) {
this.partA = partA;
}
public String getPartB() {
return partB;
}
public void setPartB(String partB) {
this.partB = partB;
}
public String getPartC() {
return partC;
}
public void setPartC(String partC) {
this.partC = partC;
}
}
```
在主函数中,我们首先创建一个ConcreteBuilder实例,并将其传递给Director构造函数中。接下来,我们通过director调用construct方法创建Product对象,并最终输出各部分的属性值。最终输出结果如下:
```
Part A: Part A
Part B: Part B
Part C: Part C
```
阅读全文