Java's creator mode is somewhat similar to the factory mode, but the focus is different. The factory pattern often only cares about what you want, but not the specific details of this thing. Relatively speaking, the creation mode is concerned with the specific details of the creation of this thing. Take creating a character as an example. We care not only about creating a character, but also about his gender, skin color and name. Then we can use the creator mode.
The program example is as follows:
package builder;/** * * DOC race role* */public class Race { private String name;// name private String skinColor;// skin color 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;/** * * DOC What we care about is not just To create a character, you also need to care about the creation of its characteristics* */public class RaceBuilder { private Race race; /** * DOC Create a race* * @return */ public RaceBuilder builder() { this.race = new Race(); return this; } /** * DOC to select a name* * @return */ public RaceBuilder setName(String name) { this.race.setName(name); return this; } /** * DOC to select a gender* * @return */ public RaceBuilder setSex(String sex) { this.race.setSex(sex); return this; } /** * DOC select skin color* * @return */ public RaceBuilder setSkinColor(String skinColor) { this.race.setSkinColor(skinColor); return this; } /** * * DOC Return this created race* * @return */ 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(); }}