建造者模式
阿新 • • 發佈:2017-06-08
logs getc sets interface class mod face pri ldm
建造者模式是對象的創建模式,可以將一個對象的內部表現和生成過程分割開來,從而使一個建造過程具有生成不同內部表現的對象的功能。
適用場景: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() { 9return 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 }
輸出:
他的模型是孫悟空 他的職業是妖魔 他的性別是男
建造者模式