状态模式-坦克大战-js

需求:

坦克在停止状态,能走和瞄准;瞄准进入,已经瞄准状态,走向进入走形中状态。

在瞄准状态,只能进行射击,射击后进入停止状态。

走行中状态,只能进行停止,不能瞄准和射击。

运行效果

代码


console.log('状态模式');
/*
//prototype 实验------------------------------------------
console.log("prototype 实验");
// 定义类A
function A(a) {
    this.a = a;
}
// 为类A定义show方法
A.prototype.show = function () {
    console.log("A: " + this.a);
}
var a = new A(5);
a.show();

// 定义类B
function B(a, b) {
    // 调用A的构造函数
    A.apply(this, arguments);
    this.b = b;
}
// 链接A的原型
B.prototype = new A();
var b = new B(100, 200);
b.show();

// 覆盖show方法
B.prototype.show = function () {
    A.prototype.show.apply(this, arguments);
    console.log("B: " + this.b);
}
// 运行覆盖后的方法
b.show();
console.log("\n");
*/
//坦克大战 ------------------------------------------
var stated = {
    stoped: "stoped",
    armed: "armed",
    runing: "runed"
}
class State {
    constructor(tank) {
        this.tank = tank;
    }
}
class Stoped extends State{
    constructor(tank) {
        super(tank);
    }
    arm() {
        console.log("瞄准");
        this.tank.change(stated.armed);
    }
    sort() {
         
    }
    run() {
        console.log("跑");
        this.tank.change(stated.runing);
    }
    stop() {

    }
}
class Aimed extends State {
    constructor(tank) {
        super(tank);        
    }
    arm() {
               
    }
    sort() {
        console.log("射击");
        this.tank.change(stated.stoped);
    }
    run() {

    }
    stop() {

    }
}
class Running extends State {
    constructor(tank) {
        super(tank);
    }
    arm(){
        console.log("请停车后瞄准");
    }
    sort(){
        
    }
    run(){

    }
    stop() {
        console.log("停止");
        this.tank.change(stated.stoped);
    }
}
class Tank{
    constructor() {
        this.stats = new Array(3);
        this.stats[0] = new Stoped(this);
        this.stats[1] = new Aimed(this);
        this.stats[2] = new Running(this);
        this.curentState = this.stats[0];
    }
    arm() {
        this.curentState.arm();   
    }
    sort() {
        this.curentState.sort();
    }
    run() {
        this.curentState.run();
    }
    stop() {
        this.curentState.stop();
    }
    change(toState) {
        if (toState == stated.stoped) {
            this.curentState = this.stats[0];
        } else if (toState == stated.armed) {
            this.curentState = this.stats[1];
        } else {
            this.curentState = this.stats[2];
        }
    }
}


// 客户端
class Client {
    main() {
        var tank = new Tank();
        tank.run();
        tank.arm();
        tank.stop();
        tank.arm();
        tank.sort();
    }
}
var client = new Client();
client.main();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值