1、简介
1.1、意图
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
1.2、适用性
当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
当构造过程必须允许被构造的对象有不同的表示时。
1.3、优点
各个具体的建造者相互独立,有利于系统的扩展。
客户端不必知道产品内部组成的细节,便于控制细节风险。
1.4、缺点
产品的组成部分必须相同,这限制了其使用范围。
如果产品的内部变化复杂,该模式会增加很多的建造者类。
2、类图
3、代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| @Data public class Car {
private String engine;
private String skeleton;
private String wheel; } public abstract class AbstractCarBuilder { protected Car car = new Car(); public abstract void buildEngine(); public abstract void buildSkeleton(); public abstract void buildWheel(); public Car getResult() { buildEngine(); buildSkeleton(); buildWheel(); return car; } } public class HighCarBuilder extends AbstractCarBuilder { @Override public void buildEngine() { car.setEngine("2.0t"); } @Override public void buildSkeleton() { car.setSkeleton("宽敞型"); } @Override public void buildWheel() { car.setWheel("防爆"); } } public class BottomCarBuilder extends AbstractCarBuilder { @Override public void buildEngine() { car.setEngine("1.5t"); } @Override public void buildSkeleton() { car.setSkeleton("紧凑型"); } @Override public void buildWheel() { car.setWheel("不防爆"); } } public class CarDirector { private AbstractCarBuilder abstractCarBuilder; public CarDirector(AbstractCarBuilder abstractCarBuilder) { this.abstractCarBuilder = abstractCarBuilder; } public Car construct() { return abstractCarBuilder.getResult(); } } public class BuilderDemo { public static void main(String[] args) { HighCarBuilder highCarBuilder = new HighCarBuilder(); CarDirector carDirector = new CarDirector(highCarBuilder); Car car = carDirector.construct(); System.out.println(car); BottomCarBuilder bottomCarBuilder = new BottomCarBuilder(); carDirector = new CarDirector(bottomCarBuilder); car = carDirector.construct(); System.out.println(car); } }
|
参考
https://blog.csdn.net/atu1111/article/details/105448694
https://blog.csdn.net/zsjlovesm521/article/details/94382666
https://blog.csdn.net/blueboz/article/details/103172559
http://c.biancheng.net/view/1354.html