什么是建造者模式?
建造者模式是将一个复杂得对象的构建与它的表示分离,使得同样的建造过程可以创建不用的表示。
主要作用?
在用户不知道对象构造过程和细节的情况下可以直接创建复杂的对象.
UML类图?
Director:指挥者直接与客户(使用者)沟通
沟通后指挥者将客户创建产品的需求划分为各个组件的建造请求(Builder)
将各个组件的建造请求委派给具体的建造者(ConcreteBulder)
具体建造者进行产品构建并返回产品信息
实例?
/**
* 产品类-小汽车组装类
* */
public class Car {
//轮胎
private String lunTai;
//发动机
private String faDongJi;
//方向盘
private String fangXiangPan;
public String getLunTai() {
return lunTai;
}
public void setLunTai(String lunTai) {
this.lunTai = lunTai;
}
public String getFaDongJi() {
return faDongJi;
}
public void setFaDongJi(String faDongJi) {
this.faDongJi = faDongJi;
}
public String getFangXiangPan() {
return fangXiangPan;
}
public void setFangXiangPan(String fangXiangPan) {
this.fangXiangPan = fangXiangPan;
}
@Override
public String toString() {
return "Car{" +
"lunTai='" + lunTai + '\'' +
", faDongJi='" + faDongJi + '\'' +
", fangXiangPan='" + fangXiangPan + '\'' +
'}';
}
}
Builder—抽象小汽车组装过程
/**
* 小汽车组装过程抽象类
* */
public abstract class Builder {
public abstract void azLunTai();
public abstract void azFaDongji();
public abstract void azFangXiangPan();
//安装完成
public abstract Car azwc();
}
与客户沟通的指挥者:
/**
* 用户用于创建复杂对象
* */
public class CarDirector{
private Builder builder;
public CarDirector(Builder builder){
this.builder = builder;
}
public Car car(){
builder.azLunTai();
builder.azFaDongji();
builder.azFangXiangPan();
return builder.azwc();
}
}
具体实现组装过程的产品类
public class BenChiCar extends Builder {
private Car car = new Car();
@Override
public void azLunTai() {
car.setLunTai("安装奔驰车轮胎");
}
@Override
public void azFaDongji() {
car.setFaDongJi("安装奔驰车发动机");
}
@Override
public void azFangXiangPan() {
car.setFangXiangPan("安装奔驰车方向盘");
}
@Override
public Car azwc() {
return car;
}
}
客户使用
public class CarTest{
public static void main(String[] args) {
CarDirector carDirector = new CarDirector(new BenChiCar());
Car car = carDirector.car();
System.out.println(car.toString());
}
}