什么是建造者模式呢,顾名思义,把某个东西创建出来,说得准确点是,把各种部件按照需要的方式建造成一个产品。建造者模式「需要四个类,抽象建造者,具体建造者,产品类,导演类」。
public class Phone {
//手机的部件
private String cpu;
private String screen;
private String camera;
//对部件的逻辑处理
public void setCpu(String cpu) {
this.cpu = cpu;
}
public void setScreen(String screen) {
this.screen = screen;
}
public void setCamera(String camera) {
this.camera = camera;
}
public String use() {
return "Phone{" +
"cpu='" + cpu + '\'' +
", screen=" + screen +
", camera=" + camera +
'}';
}
}
public abstract class AbstractBuilder {
//多个部件供我们组合成不同的产品
public abstract void midCpu();
public abstract void midScreen();
public abstract void midCamera();
public abstract void topCpu();
public abstract void topScreen();
public abstract void topCamera();
//组合完成后返回产品类
public abstract Phone buildPhone();
}
注意并不是具体的产品,而是具体的厂商,生产不同品牌部件的建造者,在本例中有两个具体建造者类,一个是生产一加的各部件,一个是生产魅族的各部件。
public class OnePlusBuilder extends AbstractBuilder {
Phone phone = new Phone();
@Override
public void midCpu() {
phone.setCpu("一加高配处理器");
}
@Override
public void midScreen() {
phone.setScreen("一加高配屏幕");
}
@Override
public void midCamera() {
phone.setCamera("一加高配相机");
}
@Override
public void topCpu() {
phone.setCpu("一加顶配处理器");
}
@Override
public void topScreen() {
phone.setScreen("一加顶配屏幕");
}
@Override
public void topCamera() {
phone.setCamera("一加顶配相机");
}
@Override
public Phone buildPhone() {
return phone;
}
}
public class MeizuBuilder extends AbstractBuilder {
Phone phone = new Phone();
@Override
public void midCpu() {
phone.setCpu("魅族中配处理器");
}
@Override
public void midScreen() {
phone.setScreen("魅族中配屏幕");
}
@Override
public void midCamera() {
phone.setCamera("魅族中配相机");
}
@Override
public void topCpu() {
phone.setCpu("魅族高配处理器");
}
@Override
public void topScreen() {
phone.setScreen("魅族高配屏幕");
}
@Override
public void topCamera() {
phone.setCamera("魅族高配相机");
}
@Override
public Phone buildPhone() {
return phone;
}
}
导演嘛,很形象,指挥要建造什么具体的产品
导演
public class Director {
AbstractBuilder builder;
public Director(AbstractBuilder builder) {
this.builder = builder;
}
public Phone buildMidPhone() {
builder.midCpu();
builder.midCamera();
builder.midScreen();
return builder.buildPhone();
}
public Phone buildTopPhone() {
builder.topCpu();
builder.topCamera();
builder.topScreen();
return builder.buildPhone();
}
}
现在不是都说手机是堆料嘛,导演类就负责,我能够用不同的料,甚至同样的料不同的堆积方法来给你堆出不同的产品。
像上面的例子中,我有6个部件,「但是不同的部件我能够生产不同的产品。」
public class Test {
public static void main(String[] args) {
Director director = new Director(new OnePlusBuilder());
System.out.println(director.buildMidPhone().use());
System.out.println(director.buildTopPhone().use());
director = new Director(new MeizuBuilder());
System.out.println(director.buildMidPhone().use());
System.out.println(director.buildTopPhone().use());
}
}
两者比较相似,但是不同的点还是比较清晰。