一、定义、使用场景及要点
在《设计模式》中原话是这样的:“separate the construction of a complex object from its representation so that the same construction process can create different representations.”
然而国内一般翻译成这样的:“将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示。”
建议直接无视翻译后的这句,我认为以国人的语言习惯翻译后的这句话带给人的误导,比带给人正确理解原意起了更大作用!还是揣摩英文原话吧。
简单理解:从简单的对象一步一步的构建一个复杂的对象。
使用场景:
|| Make a complex object by specifying only its type and content. The built object is shielded from the details of its construction.
|| Want to decouple the process of building a complex object from the parts that make up the object.
|| Isolate code for construction and representation.
|| Give you finer control over the construction process.
要点:1此模式主要用于分步骤构建一个复杂的对象,这些步骤是固定的。
2对于这个复杂对象来说,就是他的各个部分可能频繁变动。对于这些可能变动的部分进行封装。
二、架构
可以参考下这个 http://www.javacamp.org/designPattern/builder.html
class TestBuilder {
public static void main(String[] args) {
HouseBuilder one = new OneStoryHouse("2 bedrooms, 2.5 baths, 2-car garage, 1500 sqft");
HouseBuilder two = new TwoStoryHouse("4 bedrooms, 4 baths, 3-car garage, 5000 sqft");
WorkShop shop = new WorkShop();
shop.construct(one);
shop.construct(two);
System.out.println("Check house building progress: \n");
System.out.println(one.showProgress());
System.out.println(two.showProgress());
}
}
class WorkShop {
//force the order of building process
public void construct(HouseBuilder hb) {
hb.buildFoundation();
hb.buildFrame();
hb.buildExterior();
hb.buildInterior();
}
}
//set steps for building a house
abstract class HouseBuilder {
protected House house = new House();
protected String showProgress() {
return house.toString();
}
abstract public void buildFoundation();
abstract public void buildFrame();
abstract public void buildExterior();
abstract public void buildInterior();
}
class OneStoryHouse extends HouseBuilder {
public OneStoryHouse(String features) {
house.setType(this.getClass() + " " + features);
}
public void buildFoundation() {
//doEngineering()
//doExcavating()
//doPlumbingHeatingElectricity()
//doSewerWaterHookUp()
//doFoundationInspection()
house.setProgress("foundation is done");
}
public void buildFrame() {
//doHeatingPlumbingRoof()
//doElectricityRoute()
//doDoorsWindows()
//doFrameInspection()
house.setProgress("frame is done");
}
public void buildExterior() {
//doOverheadDoors()
//doBrickWorks()
//doSidingsoffitsGutters()
//doDrivewayGarageFloor()
//doDeckRail()
//doLandScaping()
house.setProgress("Exterior is done");
}
public void buildInterior() {
//doAlarmPrewiring()
//doBuiltinVacuum()
//doInsulation()
//doDryWall()
//doPainting()
//doLinoleum()
//doCabinet()
//doTileWork()
//doLightFixtureBlinds()
//doCleaning()
//doInteriorInspection()
house.setProgress("Interior is under going");
}
}
三、使用效果
面对不可预见的“复杂对象的部分”的改动需求,只要提供一个相应的Builder ,用新的Builder替换旧的就可以了。