zoukankan      html  css  js  c++  java
  • js设计模式 -- 状态机

    /*****************************抽象类***************************/
    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;
    };
    
  • 相关阅读:
    ORA16014 与 ORA00312
    ORA26687
    ORA32004问题解决
    ORA23616:执行块5失败
    Streams实践之Schemas级复制
    Streams FAQ
    ORA23622: 正在执行操作SYS.DBMS_STREAMS_ADM.MAINTAIN_GLOBAL
    为什么白帽SEO更好?
    HyperV虚拟机安装及网卡无法找到,驱动无法安装解决办法
    Memcahed分布式缓存服务替换Session解决方案——简单介绍[转]
  • 原文地址:https://www.cnblogs.com/smss/p/7357873.html
Copyright © 2011-2022 走看看