class House { public windows: string[] = []; public doors: string[] = []; public rooms: string[] = []; public area: number = 0; public parts: string[] = []; constructor() { this.setWindows("window"); this.setDoors("door"); this.setBedRooms("room"); } public listWindows(): House { console.log(`House windows: ${this.windows.join(", ")}\n`); returnthis; } public listDoors(): House { console.log(`House doors: ${this.doors.join(", ")}\n`); returnthis; } public listRooms(): House { console.log(`House rooms: ${this.rooms.join(", ")}\n`); returnthis; }
public setWindows(w: string): House { this.windows.push(w); returnthis; } public setDoors(d: string): House { this.doors.push(d); returnthis; } public setBedRooms(r: string): House { this.rooms.push(r); this.area += 30; returnthis; } public setKitchens(r: string): House { this.rooms.push(r); this.area += 20; returnthis; } public capacity(): number { returnthis.area / 15; } }
现在生活水平不断提高,我们开始有不同的要求,有车的人需要有车库的房子,有人需要有花园的,有泳池,有庭院等的房子。 一种常用的方法是,基于 House 类派生出 HouseWithGarage、HouseWithPool、HouseWithYard…
class HouseWithGarage extends House { constructor() { super(); this.setGarges("garage"); } public listGarges(): House { console.log(`House parts: ${this.parts.join(", ")}\n`); returnthis; } public setGarges(g: string): House { this.parts.push(g); returnthis; } }
const hg = new HouseWithGarage(); console.log("builderProblem.ts第63行:::hg", hg);
在 House 类中,有最终生产与配置房屋实例相关的方法(set…)。 这些方法都为构建产品而立,我们可以把这些工作都交给建筑工。
class House { public windows: string[] = []; public doors: string[] = []; public rooms: string[] = []; public area: number = 0; public parts: string[] = []; [s: string]: any; public listWindows(): House { console.log(`House windows: ${this.windows.join(", ")}\n`); returnthis; } public listDoors(): House { console.log(`House doors: ${this.doors.join(", ")}\n`); returnthis; } public listRooms(): House { console.log(`House rooms: ${this.rooms.join(", ")}\n`); returnthis; }
/** * 建筑基础房子 */ public buildMini(): void { this.builder.setBase(); }
public buildMedium(): void { this.builder.setBase().setGarges("garage").setYards("yard"); } public buildLarge(): void { this.builder .setBase() .setGarges("garage") .setYards("yard") .setPools("pool"); } }
监工的使用
const director = new Director(); const builderA = new HouseABuilder(); director.setBuilder(builderA); director.buildLarge(); const f = builderA.getHouse(); console.log("director.ts第214行:::large base house", f);
const builderB = new HouseBBuilder(); director.setBuilder(builderB); director.buildMedium(); const m = builderB.getHouse(); console.log("director.ts第214行:::medium diamond house", m);