Introduction to the creator pattern of the Java design pattern

  • 2020-04-01 03:24:52
  • OfStack

The Java creator pattern is somewhat similar to the factory pattern, but with different concerns. The factory model tends to care about what you want, not what the details are. Creating a pattern, by contrast, is about creating the details of the thing. In the case of creating a character, we care not only about creating a character, but also about his gender, skin color, and name, so we can use the creator mode.

The program example is shown as follows:


package builder;

public class Race {
  private String name;//The name
  private String skinColor;//Color of skin
  private String sex;//gender
  public String getName() {
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getSkinColor() {
    return this.skinColor;
  }
  public void setSkinColor(String skinColor) {
    this.skinColor = skinColor;
  }
  public String getSex() {
    return this.sex;
  }
  public void setSex(String sex) {
    this.sex = sex;
  }
}
package builder;

public class RaceBuilder {
  private Race race;
  
  public RaceBuilder builder() {
    this.race = new Race();
    return this;
  }
  
  public RaceBuilder setName(String name) {
    this.race.setName(name);
    return this;
  }
  
  public RaceBuilder setSex(String sex) {
    this.race.setSex(sex);
    return this;
  }
  
  public RaceBuilder setSkinColor(String skinColor) {
    this.race.setSkinColor(skinColor);
    return this;
  }
  
  public Race create() {
    return this.race;
  }
}

The test classes are as follows:


package builder;
public class Main {
  public static void main(String[] args) {
    Race race = new RaceBuilder().builder().setName(" Zhang SAN ").setSex(" male ").setSkinColor(" white ").create();
  }
}

Related articles: