写一个建造者模式的代码实例
时间: 2024-04-23 16:16:03 浏览: 79
好的,下面给您展示一个简单的建造者模式的代码实例:
```
// 产品类
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 void show() {
System.out.println("Part A: " + partA);
System.out.println("Part B: " + partB);
System.out.println("Part C: " + partC);
}
}
// 抽象建造者
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;
}
}
// 具体建造者
class ConcreteBuilder extends Builder {
public void buildPartA() {
product.setPartA("A");
}
public void buildPartB() {
product.setPartB("B");
}
public void buildPartC() {
product.setPartC("C");
}
}
// 导演类
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void construct() {
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
}
}
// 客户端类
public class BuilderPatternDemo {
public static void main(String[] args) {
Builder builder = new ConcreteBuilder();
Director director = new Director(builder);
director.construct();
Product product = builder.getResult();
product.show();
}
}
```
该代码实例演示了建造者模式的基本使用,通过建造者分步创建复杂的产品对象,并且可以改变产品对象的内部表示。希望对您有所帮助!
阅读全文