建造者模式java程序demo
时间: 2023-06-14 18:06:25 浏览: 80
好的,下面是建造者模式的Java程序示例:
```
// Product类,表示需要被构建的复杂对象
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;
}
}
// Builder类,定义了如何构建Product对象的接口
abstract class Builder {
protected Product product = new Product();
public abstract void buildPartA();
public abstract void buildPartB();
public abstract void buildPartC();
public Product getResult() {
return product;
}
}
// ConcreteBuilder类,实现了Builder接口,构建具体的Product对象
class ConcreteBuilder extends Builder {
public void buildPartA() {
product.setPartA("PartA");
}
public void buildPartB() {
product.setPartB("PartB");
}
public void buildPartC() {
product.setPartC("PartC");
}
}
// Director类,使用Builder接口来构建Product对象
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void construct() {
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
}
}
// 测试程序
public class BuilderDemo {
public static void main(String[] args) {
Builder builder = new ConcreteBuilder();
Director director = new Director(builder);
director.construct();
Product product = builder.getResult();
System.out.println(product.getPartA() + " " + product.getPartB() + " " + product.getPartC());
}
}
```
这个示例中,Product类表示需要被构建的复杂对象,Builder类定义了如何构建Product对象的接口,ConcreteBuilder类实现了Builder接口,构建具体的Product对象,Director类使用Builder接口来构建Product对象。在测试程序中,首先创建了一个ConcreteBuilder对象和一个Director对象,然后通过Director对象来构建Product对象,最后获取构建完成的Product对象并输出。
阅读全文