js设计模式 -- 状态机

本文通过JavaScript实现了一个基于状态模式的灯光控制系统。该系统包括三种状态:关灯、弱光和强光。每种状态都有对应的按钮触发行为,实现了状态之间的转换。

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

/*****************************抽象类***************************/
var State = function() {};
State.prototype.pressButton = function() {
    throw new Error('pressButton方法必须重写');
};
/*****************************状态类***************************/
//关灯状态
var OffState = function(light) {
    this.light = light;
};
OffState.prototype = new State(); //继承父类
//覆盖父类方法
OffState.prototype.pressButton = function() {
    console.log('弱光');
    this.light.setState(this.light.weak);
};
// 弱光状态
var WeakState = function(light) {
    this.light = light;
};
WeakState.prototype = new State(); //继承父类
// 覆盖父类方法
WeakState.prototype.pressButton = function() {
    console.log('强光');
    this.light.setState(this.light.strong);
};
// 强光状态
var StrongState = function(light) {
    this.light = light;
};
StrongState.prototype = new State(); //继承父类
// 覆盖父类方法
StrongState.prototype.pressButton = function() {
    console.log('关灯');
    this.light.setState(this.light.off);
};

//******************灯类********************//
var Light = function() {
    this.off = new OffState(this);
    this.weak = new WeakState(this);
    this.strong = new StrongState(this);
    this.button = null;
};
Light.prototype.init = function() {
    var button = document.createElement('button');
    var _self = this;
    this.button = document.body.appendChild(button);
    this.button.innerHTML = '三种状态开关';
    this.currentState = this.off; //设置当前状态为关闭状态
    this.button.onclick = function() {
        _self.currentState.pressButton();
    };
};
Light.prototype.setState = function(newState) {
    this.currentState = newState;
};

转载于:https://www.cnblogs.com/smss/p/7357873.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值