建造者模式
Separate the construction of a complex object from its representation so that
the same construction process can create different representations.
将一个复杂对象的构建与其表示分离,以便相同的构建过程可以创建不同的表示。
public class Constuctor {
/**
* 建造者模式:
* Separate the construction of a complex object from its representation so that
* the same construction process can create different representations.
* 将一个复杂对象的构建与其表示分离,以便相同的构建过程可以创建不同的表示。
*/
@Test
public void all() {
BenzFactory.series1().run();
BenzFactory.series2().run();
}
}
/**
* 1)定义零件类型
*/
enum CarPartEnum {
ENGINE, ALARM, VEHICLE_MOUNTED_SYSTEM, BRAKE;
}
/**
* 2)定义零件操作
*/
interface CarPart {
String name();
void doWork();
}
/**
* 3)定义具体的零件
*/
@Builder
@Slf4j
class CarPartImpl implements CarPart {
private final String name;
@Override
public void doWork() {
log.info("{} is working now", name);
}
@Override
public String name() {
return name;
}
}
/**
* 4)整合零件与操作的模型类,核心组件
*/
class CarModel {
private final List<CarPart> parts = Lists.newArrayList();
public CarModel addPart(CarPart carPart) {
parts.add(carPart);
return this;
}
public final void run() {
parts.forEach(CarPart::doWork);
}
}
/**
* 5)抽象建造者
*/
interface CarBuilder {
CarModel build();
}
/**
* 6)具体建造者
*/
class BenzSeries1CarBuilder implements CarBuilder {
private static final CarBuilder CAR_BUILDER = new BenzSeries1CarBuilder();
private BenzSeries1CarBuilder() {
}
public static CarBuilder get() {
return CAR_BUILDER;
}
@Override
public CarModel build() {
return new CarModel()
.addPart(new CarPartImpl(CarPartEnum.ENGINE.name()))
.addPart(new CarPartImpl(CarPartEnum.BRAKE.name()));
}
}
class BenzSeries2CarBuilder implements CarBuilder {
private static final CarBuilder CAR_BUILDER = new BenzSeries2CarBuilder();
private BenzSeries2CarBuilder() {
}
public static CarBuilder get() {
return CAR_BUILDER;
}
@Override
public CarModel build() {
return new CarModel()
.addPart(new CarPartImpl(CarPartEnum.ENGINE.name()))
.addPart(new CarPartImpl(CarPartEnum.VEHICLE_MOUNTED_SYSTEM.name()))
.addPart(new CarPartImpl(CarPartEnum.ALARM.name()))
.addPart(new CarPartImpl(CarPartEnum.BRAKE.name()));
}
}
/**
* 7)实例工厂
*/
class BenzFactory {
public static CarModel series1() {
return BenzSeries1CarBuilder.get().build();
}
public static CarModel series2() {
return BenzSeries2CarBuilder.get().build();
}
}