建造者,顾名思义,就是要从设计师的角度去建造一个产品,就像你造一个汽车,一部手机,这时候我们首先就需要众多零件,这些零件就是你所需要的类,同时还要合理的把这些零件组装带一起产生一个你需要的产品。
建造者模式的本质是分离了对象自组建的单独构造(由Builder来负责)和装配(由Director来负责),从而可以构造出复杂的对象。由于实现了构造和装配的解耦,不同的构造器,相同的装配过程也会产生不同的结果,不同的装配顺序也会产生不同的结果。
以制造手机为例,现在我们需要的零件(类)有主板,摄像机,屏幕
package com.panda.build;
public class Phone {
private Camera camera;
private Screen screen;
private Mainboard mainboard;
public Phone(Camera camera, Screen screen, Mainboard mainboard) {
super();
this.camera = camera;
this.screen = screen;
this.mainboard = mainboard;
}
public Phone() {
super();
// TODO Auto-generated constructor stub
}
public Camera getCamera() {
return camera;
}
public void setCamera(Camera camera) {
this.camera = camera;
}
public Screen getScreen() {
return screen;
}
public void setScreen(Screen screen) {
this.screen = screen;
}
public Mainboard getMainboard() {
return mainboard;
}
public void setMainboard(Mainboard mainboard) {
this.mainboard = mainboard;
}
}
class Camera{
private String name;
public Camera(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Screen{
private String name;
public Screen(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Mainboard{
private String anme;
public Mainboard(String anme) {
super();
this.anme = anme;
}
public String getAnme() {
return anme;
}
public void setAnme(String anme) {
this.anme = anme;
}
}
一个构造器接口和实现类
package com.panda.build;
public interface PhoneBuilder {
Camera getCamera();
Screen getScreen();
Mainboard getMainboard();
}
package com.panda.build;
public class PhoneBuilderImpl implements PhoneBuilder{
@Override
public Camera getCamera() {
Camera c = new Camera("莱卡");
return c;
}
@Override
public Screen getScreen() {
Screen s = new Screen("飞利浦");
return s;
}
@Override
public Mainboard getMainboard() {
Mainboard m = new Mainboard("华为");
return m;
}
}
一个装配器接口和实现类
package com.panda.build;
public interface PhoneDirector {
Phone getPhone();
}
package com.panda.build;
public class PhoneDirectorImpl implements PhoneDirector{
private PhoneBuilder pBuilder;
public PhoneDirectorImpl(PhoneBuilder pBuilder) {
super();
this.pBuilder = pBuilder;
}
@Override
public Phone getPhone() {
Phone phone = new Phone();
phone.setCamera(pBuilder.getCamera());
phone.setScreen(pBuilder.getScreen());
phone.setMainboard(pBuilder.getMainboard());
return phone;
}
}
然后进行测试
package com.panda.build;
public class TestPhone {
public static void main(String[] args) {
Phone phone = new PhoneDirectorImpl(new PhoneBuilderImpl()).getPhone();
phone.getCamera();
System.out.println(phone.getCamera().getName());
}
}
结果: