首页 > 代码库 > 建造者模式

建造者模式

建造者模式是对象的创建模式,可以将一个对象的内部表现和生成过程分割开来,从而使一个建造过程具有生成不同内部表现的对象的功能。

适用场景:RPG中游戏角色、视频播放软件

比如进入RPG游戏创建角色,先创建角色的模型、再创建角色的职业、再创建角色的性别等

 1 //RPG角色的对应类
 2 public class BRPGRole {
 3 
 4     private String model;
 5     private String career;
 6     private String sex;
 7     
 8     public String getModel() {
 9         return model;
10     }
11     public void setModel(String model) {
12         this.model = model;
13     }
14     public String getCareer() {
15         return career;
16     }
17     public void setCareer(String career) {
18         this.career = career;
19     }
20     public String getSex() {
21         return sex;
22     }
23     public void setSex(String sex) {
24         this.sex = sex;
25     }
26     
27 }
28 
29 public interface Builder {
30 
31     public void buildModel();
32     public void buildCareer();
33     public void buildSex();
34     public BRPGRole getResult();
35     
36 }
37 
38 //孙悟空RPG角色的创建类
39 public class WukongBuilder implements Builder {
40 
41     private BRPGRole product = new BRPGRole();
42     
43     @Override
44     public void buildModel() {
45         product.setModel("他的模型是孙悟空");
46     }
47 
48     @Override
49     public void buildCareer() {
50         product.setCareer("他的职业是妖魔");
51     }
52 
53     @Override
54     public void buildSex() {
55         product.setSex("他的性别是男");
56     }
57 
58     @Override
59     public BRPGRole getResult() {
60         return product;
61     }
62 
63 }
64 
65 public class BuilderGod {
66 
67     private Builder builder;
68     
69     public BuilderGod(Builder builder){
70         this.builder = builder;
71     }
72     
73     public void construct(){
74         builder.buildModel();
75         builder.buildCareer();
76         builder.buildSex();
77     }
78     
79 }
80 
81 public class BuilderMain {
82 
83     public static void main(String[] args) {
84         
85         Builder builder = new WukongBuilder();
86         BuilderGod builderGod = new BuilderGod(builder);
87         builderGod.construct();
88         BRPGRole role = builder.getResult();
89         System.out.println(role.getModel());
90         System.out.println(role.getCareer());
91         System.out.println(role.getSex());
92         
93     }
94 
95 }

输出:

他的模型是孙悟空
他的职业是妖魔
他的性别是男

  

建造者模式