定义
它属于创建型模式的一种,将一个复杂的对象分解成多个简单的对象来进行构建,将复杂的构建层与表示层分离,使得相同的构建过程可以创建不同的表示的模式便是建造者模式
举个栗子
现在有一个建造汽车的工厂,他们主要目的是生成汽车,汽车的标识都是相同的(大众),但是汽车轮子有不同的型号,汽车的发动机也是有不同的功率的
三个组成
抽象建造者
Car就是抽象建造者,它具备一些车的基本属性还有方法, 它是抽象的,用户不需要知道它的存在,
那么Tyre(轮胎),Engine(发动机),分别就是车的具体部件(具体类),指挥者
创建的BenChi类,其实就是一个指挥者的角色,负责把对应的部件组装起来,
具体建造者
抽象建造者
// #建造者模式// 抽象建造者var Car = function (param) {// 速度this.speed = param && param.speed || '0';// 重量this.weight = param && param.weight || '0';}Car.prototype = {// 获取速度getSpeed: function () {return this.speed;},// 获取重量getWeight: function () {return this.weight}}// 轮胎部件类var Tyre = function (type) {var that = this;// 构造器// 构造函数中通过传入的type类型设置相对应的轮胎尺寸(function (type,that) {switch (type) {case 'small':that.tyre = '小号轮胎';that.tyreIntro = '正在使用小号轮胎';break;case 'normal':that.tyre = '中号轮胎';that.tyreIntro = '正在使用中号轮胎';break;case 'big':that.tyre = '大号轮胎';that.tyreIntro = '正在使用大号轮胎';break;}})(type,this);}Tyre.prototype = {// 更换轮胎的方法changeType: function (type) {that.tyre = type;that.tyreIntro = '正在使用'+type;}}// 发动机部件类var Engine = function (type) {var that = this;// 构造器// 构造函数中通过传入的type类型设置相对应的发动机类型(function (type,that) {switch (type) {case 'small':that.engine = '小号发动机';that.engineIntro = '正在使用小号发动机';break;case 'normal':that.engine = '中号发动机';that.engineIntro = '正在使用中号发动机';break;case 'big':that.engine = '大号发动机';that.engineIntro = '正在使用大号发动机';break;}})(type,this);}Engine.prototype = {// 更换发动机的方法changeType: function (type) {that.engine = type;that.engineIntro = '正在使用'+type;}}
指挥者
/*** 指挥者,建造一个奔驰车的类* @param {*轮胎类型 small normal big} tyre* @param {*发动机类型 small normal big} engine* @param {*车辆基本属性 param.speed:速度 param.weight: 重量} param*/var BenChi = function (tyre,engine,param) {// 创建一个车辆缓存对象var _car = new Car(param);// 创建车辆的轮胎_car.tyreInfo = new Tyre(tyre);// 创建车辆的发动机_car.engineInfo = new Engine(engine);// 将创建的车辆对象返回return _car;}
具体建造者
// 具体建造者 实例化奔驰车类var benchi1 = new BenChi('small','big',{speed: 200,weight: '200'});console.log(benchi1.speed);// 200console.log(benchi1.weight);// 200console.log(benchi1.tyreInfo.tyre);// 小号轮胎console.log(benchi1.tyreInfo.tyreIntro);// 正在使用小号轮胎console.log(benchi1.engineInfo.engine);// 大号发动机console.log(benchi1.engineInfo.engineIntro);// 正在使用大号发动机
总结
优点
- 在建造者模式中,客户端不必知道产品内部组成的细节,将产品本身与产品的创建过程解耦,使得相同的创建过程可以创建不同的产品对象。
- 每一个具体建造者都相对独立,而与其他的具体建造者无关,因此可以很方便地替换具体建造者或增加新的具体建造者,用户使用不同的具体建造者即可得到不同的产品对象。
