js設計模式----Behavioral Patterns之Interpreter(3)

This pattern is different from those we’ve seen to this point as there is no real class
structure that is defined by the pattern. You can design your language interpreter
however you wish.
用下面這種機構來描述戰鬥:

(aggressor -> battle ground <- defender) -> victor

A battle between Robert Baratheon and RhaegarTargaryen at the river Trident would look like the following:

(Robert Baratheon -> River Trident <- RhaegarTargaryen) -> Robert Baratheon

The first thing we establish is a JavaScript data model for the battle like so:

class Battle {
    constructor(battleGround, agressor, defender, victor){
        this.battleGround = battleGround;
        this.agressor = agressor;
        this.defender = defender;
        this.victor = victor;
    }
}

Next we need a parser:

class Parser {
    constructor(battleText){
        this.battleText = battleText;
        this.currentIndex = 0;
        this.battleList = battleText.split("\n");
    }
    nextBattle() {
        if (!this.battleList[0])
            return null;
        var segments = this.battleList[0].match(/\((.+?)\s?->\s?(.+?)\s?<-\s?(.+?)->\s?(.+)/);
        return new Battle(segments[2],segments[1],segments[3],segments[4]);
    }
}
var text = "(Robert Baratheon -> River Trident <- RhaegarTargaryen) -> Robert Baratheon)";
var p = new Parser(text);
p.nextBattle();

As I mentioned earlier there is no fixed way to implement this pattern, so the implementation done in the preceding code is provided simply as an example. Your implementation will very likely look very different and that is just fine.
Interpreter can be a useful pattern in JavaScript. It is, however, a pretty infrequently
used pattern in most situations. The best example of a language interpreted in
JavaScript is the less language that is compiled, by JavaScript, to CSS.

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