写一个Java建造着例子
时间: 2024-03-18 11:41:34 浏览: 49
好的,以下是一个简单的Java建造者模式的例子:
假设我们有一个Product类,它有三个属性:name、price、description。我们要使用建造者模式来创建Product对象。
1. 创建Product类
```
public class Product {
private String name;
private double price;
private String description;
public Product(String name, double price, String description) {
this.name = name;
this.price = price;
this.description = description;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public String getDescription() {
return description;
}
}
```
2. 创建ProductBuilder类
```
public class ProductBuilder {
private String name;
private double price;
private String description;
public ProductBuilder setName(String name) {
this.name = name;
return this;
}
public ProductBuilder setPrice(double price) {
this.price = price;
return this;
}
public ProductBuilder setDescription(String description) {
this.description = description;
return this;
}
public Product build() {
return new Product(name, price, description);
}
}
```
3. 创建Client类
```
public class Client {
public static void main(String[] args) {
Product product = new ProductBuilder()
.setName("iPhone")
.setPrice(999.99)
.setDescription("The most advanced smartphone ever.")
.build();
System.out.println("Name: " + product.getName());
System.out.println("Price: " + product.getPrice());
System.out.println("Description: " + product.getDescription());
}
}
```
以上代码使用建造者模式创建了一个Product对象,并输出了其属性值。
通过建造者模式,我们可以更加方便地创建对象,并且可以灵活地设置对象的属性。
阅读全文