0%

生成器模式

生成器模式也称为建造者模式,将一个复杂对象的构建与表示分离,使得同样的构建过程可以创建不同的表示(Builder)

生成器模式建议将对象构造代码从产品类中抽取出来, 并将其放在一个名为生成器(Builder)的独立对象中。该设计模式实现了构建和装配的解耦,适用于复杂对象的构造。

构成

  1. 抽象生成器类(Builder)
  2. 具体生成器类
  3. 产品类

实例

生产自行车是一个复杂的过程,它包含了车架,车座等组件的生产。而车架又有碳纤维,铝合金等材质
的,车座有橡胶,真皮等材质。对于自行车的生产就可以使用建造者模式。

public class Demo {
public static void main(String[] args) {
BikeBuilder bb = new BikeBuilder();
Bike bike = bb.createBike();
}
}

class Bike{
private String frame;
private String seat;

public String getFrame() {
return frame;
}

public void setFrame(String Frame) {
this.frame = frame;
}

public String getSeat() {
return seat;
}

public void setSeat(String seat) {
this.seat = seat;
}
}
abstract class Builder{
protected Bike mBike = new Bike(); //对子类可见
public abstract void buildFrame();
public abstract void buildSeat();
public abstract Bike createBike();
}

class BikeBuilder extends Builder{

@Override
public void buildFrame() {
mBike.setFrame("铝合金车架");
}

@Override
public void buildSeat() {
mBike.setFrame("真皮车座");
}

@Override
public Bike createBike() {
return mBike;
}
}

如果参数很多,还可以使用链式的Builder,如下示例:


public class Demo2 {
Phone phone = new Phone.Builder().cpu("AMD").screen("LG").mainboard("ASUS").memory("WD").build();
}
class Phone {
private String cpu;
private String screen;
private String memory;
private String mainboard;

public Phone(Builder builder){
cpu = builder.cpu;
screen = builder.screen;
memory = builder.memory;
mainboard = builder.mainboard;
}
public static final class Builder{
private String cpu;
private String screen;
private String memory;
private String mainboard;
public Builder(){};

public Builder cpu(String cpu){
this.cpu = cpu;
return this;
}
public Builder screen(String screen){
this.screen = screen;
return this;
}
public Builder memory(String memory){
this.memory = memory;
return this;
}
public Builder mainboard(String mainboard){
this.mainboard = mainboard;
return this;
}
public Phone build(){
return new Phone(this);
}
}
}