JavaScript 模板方法模式

146 阅读1分钟

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

简单来说,就和单机剧情游戏一样,不管你用什么角色玩,主线都是一样走的,然后各种随机的支线任务随你心意做。

class Game {
    constructor(role, branchs) {
        this.role = role
        this.branchs = branchs
    }
    
    init() {
        this.start()
        this.levelUp()
        this.branch()
        this.end()
    }
    
    start() {
        console.log('开场CG动画')
    }
    
    levelUp() {
        console.log(`${this.role.name} level ${this.role.level},打怪升级`)
        console.log(`level up! ${this.role.name} level ${++this.role.level}`)
        console.log(`level up! ${this.role.name} level ${++this.role.level}`)
        console.log(`level up! ${this.role.name} level ${++this.role.level}`)
        console.log(`level up! ${this.role.name} level ${++this.role.level}`)
    }
    
    branch() {
        if(this.branchs && this.branchs.length > 0) {
            this.branchs.forEach( item => item() )
        }
    }
    
    end() {
        console.log('游戏结束')
    }
}

class Role {
    constructor(name) {
        this.name = name
        this.level = 1
    }
}

function branch1() { console.log('拯救了少女') }
function branch2() { console.log('和少女约定,打最终BOSS就回来结婚') }

const game1 = new Game(new Role('master'))
const game2 = new Game(new Role('warrior'), [branch1, branch2])

game1.init()
game2.init()