某游戏软件中⾓⾊包括多种类型,不同类型的⼈物⾓⾊,其性别、服装、发型等外部特征 有所差异,使⽤建造者模式创建⼈物⾓⾊对象。 要求: 1. ⾄少两个具体建造者。 2. ⾓⾊有display()⽅法展⽰其性别,服装和发型(字符串表⽰),并在main中调 ⽤。
时间: 2024-12-11 20:31:02 浏览: 5
PHP颜⾊全部代码汇总.docx
建造者模式是一种工厂方法的变体,它用于将复杂对象的构建步骤分解成一系列的步骤,使得每一步可以独立地改变,而无需修改原有构造函数。在这个游戏软件中,我们可以创建两个具体的建造者类,分别对应男性和女性角色的不同外观特征:
1. **男性角色建造者 (MaleBuilder)**:
```java
public class MaleBuilder {
private String gender;
private String clothing;
private String hairstyle;
public MaleBuilder(String gender) {
this.gender = gender;
}
public void setClothing(String clothing) {
this.clothing = clothing;
}
public void setHairstyle(String hairstyle) {
this.hairstyle = hairstyle;
}
public Character build() {
return new Character(gender, clothing, hairstyle);
}
}
// 具体展示方法
public class Character implements Displayable {
private String gender;
private String clothing;
private String hairstyle;
// 构造方法省略...
@Override
public void display() {
System.out.println("性别:" + gender + ", 服装:" + clothing + ", 发型:" + hairstyle);
}
}
```
2. **女性角色建造者 (FemaleBuilder)**:
```java
public class FemaleBuilder extends MaleBuilder {
public FemaleBuilder(String gender) {
super(gender); // 继承父类,设置性别
}
@Override
public void setClothing(String clothing) {
// 对女性角色的服装做特殊处理,比如添加裙子等
if ("female".equals(gender)) {
super.setClothing("女式" + clothing);
} else {
super.setClothing(clothing);
}
}
// 可能还需要重写setHairstyle方法以适应女性发型
}
```
在`main`函数中,你可以这样使用这两个建造者来创建角色并展示它们的特性:
```java
public static void main(String[] args) {
MaleBuilder maleBuilder = new MaleBuilder("male");
maleBuilder.setClothing("牛仔裤");
maleBuilder.setHairstyle("短发");
Character maleCharacter = maleBuilder.build();
maleCharacter.display();
FemaleBuilder femaleBuilder = new FemaleBuilder("female");
femaleBuilder.setClothing("连衣裙");
femaleBuilder.setHairstyle("长发");
Character femaleCharacter = femaleBuilder.build();
femaleCharacter.display();
}
```
阅读全文