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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章