Bike
package com.jmj.pattern.builder.demo01;public class Bike {private String frame;//车架private String seat;//车座public String getFrame() {return frame;}public void setFrame(String frame) {this.frame = frame;}public String getSeat() {return seat;}public void setSeat(String seat) {this.seat = seat;}@Overridepublic String toString() {return "Bike{" +"frame='" + frame + '\'' +", seat='" + seat + '\'' +'}';}
}
Builder
package com.jmj.pattern.builder.demo01;public abstract class Builder {//声明bike类型的变量,并进行复制protected Bike bike=new Bike();public abstract void buildFrame();public abstract void buildSeat();public abstract Bike createBike();}
MobileBuilder
package com.jmj.pattern.builder.demo01;
//具体的构建者,用来构建摩拜单车对象
public class MobileBuilder extends Builder{@Overridepublic void buildFrame() {bike.setFrame("碳纤维车架");}@Overridepublic void buildSeat() {bike.setSeat("真皮车座");}@Overridepublic Bike createBike() {return bike;}
}
OfoBuilder
package com.jmj.pattern.builder.demo01;public class OfoBuilder extends Builder{@Overridepublic void buildFrame() {bike.setFrame("铝合金车架");}@Overridepublic void buildSeat() {bike.setSeat("橡胶车座");}@Overridepublic Bike createBike() {return bike;}
}
Director
package com.jmj.pattern.builder.demo01;public class Director {//声明builder类型的变量private Builder builder;public Director(Builder builder) {this.builder = builder;}//组装自行车public Bike construct(){builder.buildFrame();builder.buildSeat();return builder.createBike();}
}
Client
package com.jmj.pattern.builder.demo01;public class Client {public static void main(String[] args) {//创建指挥者对象Director director = new Director(new OfoBuilder());//让指挥者指挥组装自行车Bike construct = director.construct();System.out.println(construct);}
}
另一种建造者模式
package com.jmj.pattern.builder.demo02;public class Phone {private String cpu;private String screen;private String memory;private String mainboard;private Phone(Builder builder){this.cpu = builder.cpu;this.screen = builder.screen;this.memory = builder.memory;this.mainboard = builder.mainboard;};@Overridepublic String toString() {return "Phone{" +"cpu='" + cpu + '\'' +", screen='" + screen + '\'' +", memory='" + memory + '\'' +", mainboard='" + mainboard + '\'' +'}';}public static final class Builder{private String cpu;private String screen;private String memory;private String mainboard;public Builder cpu(String cpu){this.cpu=cpu;return this;}public Builder screen(String screen){this.screen=screen;return this;}public Builder memory(String memory){this.memory=memory;return this;}public Builder mainboard(String mainboard){this.mainboard=mainboard;return this;}//使用构建者创建Phone对象public Phone build(){return new Phone(this);}}}
package com.jmj.pattern.builder.demo02;public class Client {public static void main(String[] args) {//创建手机对象Phone.Builder builder = new Phone.Builder();Phone build = builder.cpu("英特尔").mainboard("华硕").memory("金士顿").screen("hkc").build();System.out.println(build);}
}