js设计模式----Behavioral Patterns之Interpreter(3)

本文介绍了一种使用JavaScript实现的战斗解析器设计模式。通过构造Battle类和Parser类,可以解析战斗场景并创建战斗实例。例如,罗伯特·拜拉席恩与雷加·坦格利安在三叉戟河的战斗被解析为一个具体的战斗对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值