举一个列子,手机有很多小零件组成,这里我假设手机只有手机壳,电池和屏幕三个部分组成
电池
//电池
public class Battery {
String name;
public Battery(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
屏幕
//屏幕
public class Screen {
String name;
public Screen(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
手机壳
//手机壳
public class MobileShell {
String name;
public MobileShell(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
获得所有零件
//获得手机零件
public class Mobile {
Battery battery;
MobileShell shell;
Screen screen;
public Battery getBattery() {
return battery;
}
public void setBattery(Battery battery) {
this.battery = battery;
}
public MobileShell getShell() {
return shell;
}
public void setShell(MobileShell shell) {
this.shell = shell;
}
public Screen getScreen() {
return screen;
}
public void setScreen(Screen screen) {
this.screen = screen;
}
}
定义builder接口
public interface MobileBuilder {
Battery builderBattery();
MobileShell builderMobileShell();
Screen builderScreen();
}
定义一个director接口将手机装配起来
//把手机组装起来
public interface MobileDirector {
Mobile directorMobile();
}
建造一个vivo手机所有需要的零件
public class VivoMobileBuilder implements MobileBuilder {
@Override
public Battery builderBattery() {
return new Battery("vivo电池");
}
@Override
public MobileShell builderMobileShell() {
return new MobileShell("vivo手机壳");
}
@Override
public Screen builderScreen() {
return new Screen("vivo屏幕");
}
}
将所有零件装配起来
public class VivoMobileDirector implements MobileDirector {
VivoMobileBuilder builder;
public VivoMobileDirector(VivoMobileBuilder builder) {
this.builder = builder;
}
@Override
public Mobile directorMobile() {
Battery battery = builder.builderBattery();
MobileShell mobileShell = builder.builderMobileShell();
Screen screen = builder.builderScreen();
//组装起来
Mobile mobile = new Mobile()
;
mobile.setBattery(battery);
mobile.setScreen(screen);
mobile.setShell(mobileShell);
return mobile;
}
}
测试
VivoMobileDirector director = new VivoMobileDirector(new VivoMobileBuilder());
Mobile mobile = director.directorMobile();
Screen screen = mobile.getScreen();
System.out.println( screen.getName()+mobile.getBattery().getName()+mobile.getShell().getName());
builder是将所有零件建造出来,director将所有东西装配起来