GOF设计模式——建造者模式
作者:互联网
建造者模式
public class Car {
private String name;//必选 车名
private int money;//必选 车加钱
private String type;//可选 车类型
private String colour;//可选 车颜色
public Car(String name, int money) {
this.name = name;
this.money = money;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return money == car.money && Objects.equals(name, car.name) && Objects.equals(type, car.type) && Objects.equals(colour, car.colour);
}
public void setType(String type) {
this.type = type;
}
public void setColour(String colour) {
this.colour = colour;
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", money=" + money +
", type='" + type + '\'' +
", colour='" + colour + '\'' +
'}';
}
}
/**
* 抽象构建类
*/
public abstract class CarBuilder {
public abstract void setType();
public abstract void setColour();
public abstract Car getCar();
}
/**
* 实现构建类
*/
public class ADCarBuilder extends CarBuilder {
private Car car;
public ADCarBuilder(String name, int money) {
this.car = new Car(name, money);
}
@Override
public void setType() {
car.setType("越野");
}
@Override
public void setColour() {
car.setColour("黑色");
}
@Override
public Car getCar() {
return car;
}
}
/**
* 实现构建类
*/
public class BMCarBuilder extends CarBuilder {
private Car car;
public BMCarBuilder(String name, int money) {
car = new Car(name, money);
}
@Override
public void setType() {
car.setType("小轿车");
}
@Override
public void setColour() {
car.setColour("蓝色");
}
@Override
public Car getCar() {
return car;
}
}
/**
* 指导者类
*/
public class CarDirector {
public void makeCar(CarBuilder builder) {
builder.setColour();
builder.setType();
}
}
测试建造者模式
/**
* 建造者模式
*/
public class TextBuilder {
public static void main(String[] args) {
//1
CarDirector carDirector = new CarDirector();
BMCarBuilder bmCarBuilder = new BMCarBuilder("宝马", 300000);
//构建
carDirector.makeCar(bmCarBuilder);
System.out.println(bmCarBuilder.getCar());
//2
ADCarBuilder adCarBuilder = new ADCarBuilder("奥迪", 400000);
carDirector.makeCar(adCarBuilder);
System.out.println(adCarBuilder.getCar());
}
}
测试结果:
Car{name=‘宝马’, money=300000, type=‘小轿车’, colour=‘蓝色’}
Car{name=‘奥迪’, money=400000, type=‘越野’, colour=‘黑色’}
标签:name,Car,car,GOF,建造,money,设计模式,public,String 来源: https://blog.csdn.net/lk0530/article/details/122213525