public class Bike { private IFrame frame; private ISeat seat; private ITire tire; public IFrame getFrame() { return frame; } public void setFrame(IFrame frame) { this.frame = frame; } public ISeat getSeat() { return seat; } public void setSeat(ISeat seat) { this.seat = seat; } public ITire getTire() { return tire; } public void setTire(ITire tire) { this.tire = tire; } }
// 抽象 builder 类 public abstract class Builder { abstract void buildFrame(); abstract void buildSeat(); abstract void buildTire(); abstract Bike createBike(); }
// 具体 builder 类 public class MobikeBuilder extends Builder{ private Bike mBike = new Bike(); @Override void buildFrame() { mBike.setFrame(new AlloyFrame()); } @Override void buildSeat() { mBike.setSeat(new DermisSeat()); } @Override void buildTire() { mBike.setTire(new SolidTire()); } @Override Bike createBike() { return mBike; } } public class OfoBuilder extends Builder{ private Bike mBike = new Bike(); @Override void buildFrame() { mBike.setFrame(new CarbonFrame()); } @Override void buildSeat() { mBike.setSeat(new RubberSeat()); } @Override void buildTire() { mBike.setTire(new InflateTire()); } @Override Bike createBike() { return mBike; } }
public class Director { private Builder mBuilder = null; public Director(Builder builder) { mBuilder = builder; } public Bike construct() { mBuilder.buildFrame(); mBuilder.buildSeat(); mBuilder.buildTire(); return mBuilder.createBike(); } }
个人理解:建造者模式就是应用在那些属性比较多,比较复杂的类中。不用自己来创建类,只需要交给director来给你组织,然后交给builder去完成.