Java设计模式【之】建造者模式【场景:汽车零件组装】
1.建造者模式(简述与场景)
- 举例场景:组装汽车
1.一个产品类,汽车(存在多个属性:底盘、车身、车轮、引擎、其他、品牌) 2.一个抽象构造者类,内部组合一个产品 3.一个实现类,实现抽象构造者,组装车辆 4.一般形式:构造者类通过返回 builder()对象,然后一串链式调用,最后 .build() 返回对象
- 框架中的应用:
1.JDK : StringBuffer(线程安全) StringBuilder 2.Guava : 里的不可变对象 3.MyBatis : SqlSessionFactoryBuild 里的 双层 Builder( XMLConfigBuilder() )
2.场景代码实现
2.1.汽车(产品)
public class Car {
public String chassis = "未知";
public String body = "未知";
public String wheel = "未知";
public String engine = "未知";
public String other = "未知";
public String brand = "未知";
@Override
public String toString() {
return "Car{" +
"chassis='" + chassis + '\'' +
", body='" + body + '\'' +
", wheel='" + wheel + '\'' +
", engine='" + engine + '\'' +
", other='" + other + '\'' +
", brand='" + brand + '\'' +
'}';
}
}
2.2.构造者抽象类(建造者)
public abstract class AbstractCarBuilder {
Car car = new Car();
abstract AbstractCarBuilder buildChassis(String str);
abstract AbstractCarBuilder buildBody(String str);
abstract AbstractCarBuilder buildWheel(String str);
abstract AbstractCarBuilder buildEngine(String str);
abstract AbstractCarBuilder buildOther(String str);
abstract AbstractCarBuilder buildBrand(String str);
abstract Car build();
}
2.3.构造者实现(建造者)
public class JBCarBuilder extends AbstractCarBuilder {
@Override
JBCarBuilder buildChassis(String str) {
this.car.chassis = str;
return this;
}
@Override
JBCarBuilder buildBody(String str) {
this.car.body = str;
return this;
}
@Override
JBCarBuilder buildWheel(String str) {
this.car.wheel = str;
return this;
}
@Override
JBCarBuilder buildEngine(String str) {
this.car.engine = str;
return this;
}
@Override
JBCarBuilder buildOther(String str) {
this.car.other = str;
return this;
}
@Override
JBCarBuilder buildBrand(String str) {
this.car.brand = str;
return this;
}
@Override
Car build() {
if (this.car.chassis.equals("未知")) {
System.out.println("警告:生产失败。失败原因:未安装车身....");
return null;
}
return this.car;
}
}
2.4.客户端调用
public class _Test {
public static void main(String[] args) {
JBCarBuilder jbCarBuilder =
new JBCarBuilder()
.buildChassis("JB底盘")
.buildBody("JB专用车身")
.buildWheel("JB车轮")
.buildEngine("JB引擎")
.buildOther("随便找点零件")
.buildBrand("J B");
jbCarBuilder.buildOther("JB专用零件");
Car build = jbCarBuilder.build();
System.out.println(build.toString());
StringBuilder sb =
new StringBuilder()
.append("123")
.append("2")
.append("3");
String s = sb.toString();
System.out.println(s);
}
}
3.源码下载
《七大设计原则》
《目录:Java设计模式》
《幕》
- 留白 —<老吉>
- ~ 今 ~ ? ~ ?????????? ?????????? ???????
|