构建者模式主要是用在构建复杂对象中,将多个简单对象一步步构建成复杂对象。
首先创建Computer对象(复杂对象),其中包含几个简单对象:
public class Computer {
//显示器
private String xianshiqi;
//主机
private String zhuji;
//鼠标
private String shubiao;
//键盘
private String jianpan;
//音响
private String yinxaing;
@Override
public String toString() {
return "Computer{" +
"xianshiqi='" + xianshiqi + '\'' +
", zhuji='" + zhuji + '\'' +
", shubiao='" + shubiao + '\'' +
", jianpan='" + jianpan + '\'' +
", yinxaing='" + yinxaing + '\'' +
'}';
}
public String getXianshiqi() {
return xianshiqi;
}
public void setXianshiqi(String xianshiqi) {
this.xianshiqi = xianshiqi;
}
public String getZhuji() {
return zhuji;
}
public void setZhuji(String zhuji) {
this.zhuji = zhuji;
}
public String getShubiao() {
return shubiao;
}
public void setShubiao(String shubiao) {
this.shubiao = shubiao;
}
public String getJianpan() {
return jianpan;
}
public void setJianpan(String jianpan) {
this.jianpan = jianpan;
}
public String getYinxaing() {
return yinxaing;
}
public void setYinxaing(String yinxaing) {
this.yinxaing = yinxaing;
}
}
ComputerBuilder对象,用来构建每个简单对象
public class ComputerBuilder {
private Computer computer = new Computer();
public void installXianshiqi(String xianshiqi) {
computer.setXianshiqi(xianshiqi);
}
public void installShubiao(String shubiao) {
computer.setShubiao(shubiao);
}
public void installJianpan(String jianpan) {
computer.setJianpan(jianpan);
}
public void installYinxiang(String yinxiang) {
computer.setYinxaing(yinxiang);
}
public void installZhuji(String zhuji) {
computer.setZhuji(zhuji);
}
public Computer getComputer() {
return computer;
}
}
创建测试方法:
public static void main(String[] args) {
ComputerBuilder computerBuilder = new ComputerBuilder();
computerBuilder.installJianpan("键盘");
computerBuilder.installShubiao("鼠标");
computerBuilder.installXianshiqi("显示器");
computerBuilder.installYinxiang("音响");
computerBuilder.installZhuji("主机");
System.out.println(computerBuilder.getComputer());
}
打印结果: