橋接模式,將抽象部分與它的實現部分分離,使他們都可以獨立地變化
使用組合關係代替繼承關係,降低抽象和實現兩個可變緯度的耦合度
// 用橋接模式 實現工廠生產洗衣機的不同型號
// 組裝洗衣機
function Washer(motorType, rollerType, transducerType) {
this.motor = new Motor(motorType);
this.roller = new Roller(rollerType);
this.transducer = new Transducer(transducerType);
}
// 洗衣機工作
Washer.prototype.work = function() {
this.motor.run();
this.roller.run();
this.transducer.run();
};
// 電機
function Motor(type) {
this.motorType = type + "電機";
}
Motor.prototype.run = function() {
console.log(this.motorType + "開始工作");
};
// 滾筒
function Roller(type) {
this.rollerType = type + "滾筒";
}
Roller.prototype.run = function() {
console.log(this.rollerType + "開始工作");
};
// 變頻器
function Transducer(type) {
this.transducerType = type + "變頻器";
}
Transducer.prototype.run = function() {
console.log(this.transducerType + "開始工作");
};
// 新建洗衣機
var washerA = new Washer("小功率", "直立", "小功率");
washerA.work();
var washerB = new Washer("中功率", "滾筒", "中功率");
washerB.work();
// es6實現
class Washer2 {
constructor(motorType, rollerType, transducerType) {
this.motor = new Motor2(motorType);
this.roller = new Roller2(rollerType);
this.transducer = new Transducer2(transducerType);
}
work() {
this.motor.run();
this.roller.run();
this.transducer.run();
}
}
class Motor2 {
constructor(motorType) {
this.motorType = motorType + "電機";
}
run() {
console.log(this.motorType + "開始工作");
}
}
class Roller2 {
constructor(rollerType) {
this.rollerType = rollerType + "滾筒";
}
run() {
console.log(this.rollerType + "開始工作");
}
}
class Transducer2 {
constructor(transducerType) {
this.transducerType = transducerType + "變頻器";
}
run() {
console.log(this.transducerType + "開始工作");
}
}
let washerA1 = new Washer2("大功率", "橫滾", "中等變頻");
washerA1.work();