我想消除太多" new"在我的代码中创建。 所以我决定使用构建器模式。如果可能的话,我也想利用Spring @Autowired。
public class Car
{
@Autowired
private Radio radio;
@Autowired
private Speaker speaker;
@Autowired
private Engine engine;
private String model;
public Car createCar()
{
radio.add(speaker);
return this;
}
public static class Builder
{
private String model;
public Builder(){}
public Builder model(String model)
{
this.model = model;
return this;
}
}
}
我想使用这样的东西。
Car car = new Car.Builder().model("A123").build();
这可能吗?
答案 0 :(得分:0)
好的你可以使用类似于一些基本变化的东西 首先使用默认的自动装配实例制作汽车和构建器,然后根据需要更改示例:
Car.calss
public class Car {
private Radio radio;
private Speaker speaker;
private Engine engine;
public Car(Radio radio, Speaker speaker, Engine engine) {
this.radio = radio;
this.speaker = speaker;
this.engine = engine;
}
public Radio getRadio() {
return radio;
}
public void setRadio(Radio radio) {
this.radio = radio;
}
public Speaker getSpeaker() {
return speaker;
}
public void setSpeaker(Speaker speaker) {
this.speaker = speaker;
}
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
}
CarBuilder.class
@Component
public class CarBuilder {
@Autowired
private Radio radio;
@Autowired
private Speaker speaker;
@Autowired
private Engine engine;
public CarBuilder setRadio(Radio radio) {
this.radio = radio;
return this;
}
public CarBuilder setSpeaker(Speaker speaker) {
this.speaker = speaker;
return this;
}
public CarBuilder setEngine(Engine engine) {
this.engine = engine;
return this;
}
public Car createCar() {
return new Car(radio, speaker, engine);
}
}
并在代码中使用构建器,如下所示
@Component
public class CarMarket {
@Autowired
private CarBuilder carBuilder;
private Car buildStandardCar(){
return carBuilder.createCar();
}
private Car buildStandardCarButDifferentRadio(Radio radio){
return carBuilder.setRadio(radio).createCar();
}
}
我希望这会对你有所帮助:)。
答案 1 :(得分:-1)
我认为这应该有效:
@Component
public class Car {
@Autowired
private Radio radio;
@Autowired
private Speaker speaker;
@Autowired
private Engine engine;
private String model;
}
然后是构建器类:
@Component
public class CarBuilder{
@Autowired
Car car;
public void addModel(String model){
this.car.setModel(model);
}
public Car getCar(){
return car;
}
}
然后是主课
class Main{
public static void main(String args[]){
Car car= context.getBean("carBuilder").addModel("abc").getCar();
}
}