标准建造模式的Java代码
时间: 2023-07-10 16:07:14 浏览: 79
Builder模式代码-一个java类
4星 · 用户满意度95%
标准建造模式(Builder Pattern)的Java代码实现如下:
```java
public class Product {
private String partA;
private String partB;
private String partC;
public void setPartA(String partA) {
this.partA = partA;
}
public void setPartB(String partB) {
this.partB = partB;
}
public void setPartC(String partC) {
this.partC = partC;
}
public String getPartA() {
return partA;
}
public String getPartB() {
return partB;
}
public String getPartC() {
return partC;
}
}
public interface Builder {
void buildPartA();
void buildPartB();
void buildPartC();
Product getResult();
}
public class ConcreteBuilder implements Builder {
private Product product = new Product();
@Override
public void buildPartA() {
product.setPartA("PartA");
}
@Override
public void buildPartB() {
product.setPartB("PartB");
}
@Override
public void buildPartC() {
product.setPartC("PartC");
}
@Override
public Product getResult() {
return product;
}
}
public class Director {
public void construct(Builder builder) {
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
}
}
// 使用示例
public class Client {
public static void main(String[] args) {
ConcreteBuilder builder = new ConcreteBuilder();
Director director = new Director();
director.construct(builder);
Product product = builder.getResult();
System.out.println(product.getPartA());
System.out.println(product.getPartB());
System.out.println(product.getPartC());
}
}
```
以上代码中,`Product`是需要被构建的对象,`Builder`是抽象的建造者接口,定义了具体的建造方法;`ConcreteBuilder`是具体的建造者类,实现了建造方法;`Director`是建造过程的指导者,负责按照特定的顺序调用建造方法构建对象;`Client`是客户端类,负责调用指导者构建对象。
阅读全文