java 建造者遇到继承
时间: 2023-10-11 18:23:25 浏览: 42
在 Java 中,建造者模式通常用于创建复杂的对象。如果你要使用继承来扩展现有的建造者类,可以考虑使用模板方法模式。
首先,创建一个基础建造者类,其中包含所有通用的建造逻辑。然后,创建一个抽象的建造者扩展类,该类继承自基础建造者类,并添加特定的建造逻辑。最后,创建一个具体的建造者类,该类扩展自抽象建造者类,并实现特定的建造逻辑。
举个例子,假设你要创建一个餐厅菜单项对象,其中包含名称、描述、价格和分类。你可以使用建造者模式来创建该对象,并使用继承来扩展现有的建造者类。以下是一个示例代码:
```
public class MenuItemBuilder {
protected String name;
protected String description;
protected double price;
protected String category;
public MenuItemBuilder withName(String name) {
this.name = name;
return this;
}
public MenuItemBuilder withDescription(String description) {
this.description = description;
return this;
}
public MenuItemBuilder withPrice(double price) {
this.price = price;
return this;
}
public MenuItemBuilder withCategory(String category) {
this.category = category;
return this;
}
public MenuItem build() {
return new MenuItem(name, description, price, category);
}
}
public abstract class AbstractMenuItemBuilder extends MenuItemBuilder {
public abstract AbstractMenuItemBuilder withSpecial(String special);
}
public class VeganMenuItemBuilder extends AbstractMenuItemBuilder {
private String special;
public VeganMenuItemBuilder withSpecial(String special) {
this.special = special;
return this;
}
public MenuItem build() {
MenuItem menuItem = super.build();
menuItem.setSpecial(special);
return menuItem;
}
}
```
在上面的示例代码中,`MenuItemBuilder` 是基础建造者类,它包含了所有通用的建造逻辑。`AbstractMenuItemBuilder` 是抽象建造者扩展类,它继承自 `MenuItemBuilder` 并添加了一个抽象方法 `withSpecial`。`VeganMenuItemBuilder` 是具体建造者类,它扩展自 `AbstractMenuItemBuilder` 并实现了 `withSpecial` 方法。
使用该建造者模式,你可以像下面这样创建一个餐厅菜单项对象:
```
MenuItem menuItem = new VeganMenuItemBuilder()
.withName("Vegan Burger")
.withDescription("Delicious vegan burger with lettuce, tomato and avocado.")
.withPrice(8.99)
.withCategory("Main")
.withSpecial("Gluten-free bun available on request.")
.build();
```
这里使用 `VeganMenuItemBuilder` 来创建一个餐厅菜单项对象,它继承了 `AbstractMenuItemBuilder`,并添加了特定的建造逻辑。最后,调用 `build` 方法来创建菜单项对象并返回。