js设计模式之Structural Patterns------Bridge(2)

The bridge pattern takes the adapter pattern to a new level. Given an interface, we
can build multiple adapters, each one of which acts as an intermediary to a different
implementation.

The first thing we need is a number of different gods to which we can pray:

class OldGods{
    prayTo(sacrifice){
        console.log("We Old Gods hear your prayer");
    }
}
Religion.OldGods = OldGods;
class DrownedGod {
    prayTo(humanSacrifice) {
        console.log("*BUBBLE* GURGLE");
    }
}
Religion.DrownedGod = DrownedGod;
class SevenGods {
    prayTo(prayerPurpose){
        console.log("Sorry there are a lot of us, it gets confusing here. Did you pray for something");
    }
}
Religion.SevenGods = SevenGods;

You may notice, however, that the signature for the prayTo method for each religion is
slightly different. This proves to be something of an issue when building a consistent
interface like the one shown in pseudo code here:

interface God
{
  prayTo():void;
}

So let’s slot in a few adapters to act as a bridge between the classes we have and the
signature we would like the following:

class OldGodsAdapter {
    constructor(){
        this._oldGods = new OldGods();
    }
    prayTo() {
        let sacrifice = new Sacrifice();
        this._oldGods.prayTo(sacrifice);
    }
}
Religion.OldGodsAdapter = OldGodsAdapter;
class DrownedGodAdapter {
    constructor() {
        this._drownedGod = new DrownedGod();
    }
    prayTo() {
        let sacrifice = new HumanSacrifice();
        this._drownedGod.prayTo(sacrifice);
    }
}
Religion.DrownedGodAdapter = DrownedGodAdapter;
class SevenGodsAdapter {
    constructor(){
        this.prayerPurposeProvider = new PrayPurposeProvider();
        this._sevenGods = new SevenGods();
    }
    prayTo() {
        this._sevenGods.prayTo(this.prayerPurposeProvider.GetPurpose());
    }
}
Religion.SevenGodsAdapter = SevenGodsAdapter;
class PrayerPurposeProvider {
    GetPurpose (){}
}
Religion.PrayerPurposeProvider = PrayerPurposeProvider;

Each one of these adapters implements the God interface we wanted and abstracts
away the complexity of dealing with three different interfaces, one for each god:
To use the Bridge pattern, we could write code like so:

let god1 = new Religion.SevenGodsAdapter();
let god2 = new Religion.DrownedGodAdapter();
let god3 = new Religion.OldGodsAdapter();

let gods = [god1,god2,god3];
for (let i =0; i<gods.length; i++){
    gods[i].prayTo();
}

Because there are no interfaces in JavaScript, the bridge pattern is far closer to the adapter in JavaScript than in other languages. In fact, it is basically exactly the same.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值