需求:
坦克在停止状态,能走和瞄准;瞄准进入,已经瞄准状态,走向进入走形中状态。
在瞄准状态,只能进行射击,射击后进入停止状态。
走行中状态,只能进行停止,不能瞄准和射击。
运行效果
代码
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();