


Learn the state pattern of JavaScript design patterns_javascript skills
The key to the state model is to distinguish the internal state of things. Changes in the internal state of things often bring about changes in the behavior of things.
When the light is on, if you press the switch, the light will switch to off state; if you press the switch again, the light will turn on again. The same switch behaves differently in different states.
1. Finite state machine
- The total number of states (state) is limited.
- At any moment, you are only in one state.
-
Under certain conditions, there will be a transition from one state to another.
Allows an object to change its behavior when its internal state changes, making the object appear to modify its class.
Explanation:
(1) Encapsulate the state into an independent class and delegate the request to the current state object. When the internal state of the object changes, different behavior changes will occur.
(2) The objects used have completely different behaviors (delegation effect) in different states
When it comes to encapsulation, priority is generally given to encapsulating the behavior of the object rather than the state of the object.
But in the state pattern, it's just the opposite. The key to the state pattern is to encapsulate each state of things into a separate class.
2. Example
Lighting program (low light –> strong light –> light off) cycle
// 关灯 var OffLightState = function(light) { this.light = light; }; // 弱光 var OffLightState = function(light) { this.light = light; }; // 强光 var StrongLightState = function(light) { this.light = light; }; var Light = function(){ /* 开关状态 */ this.offLight = new OffLightState(this); this.weakLight = new WeakLightState(this); this.strongLight = new StrongLightState(this); /* 快关按钮 */ this.button = null; }; Light.prototype.init = function() { var button = document.createElement("button"), self = this; this.button = document.body.appendChild(button); this.button.innerHTML = '开关'; this.currentState = this.offLight; this.button.click = function() { self.currentState.buttonWasPressed(); } }; // 让抽象父类的抽象方法直接抛出一个异常(避免状态子类未实现buttonWasPressed方法) Light.prototype.buttonWasPressed = function() { throw new Error("父类的buttonWasPressed方法必须被重写"); }; Light.prototype.setState = function(newState) { this.currentState = newState; }; /* 关灯 */ OffLightState.prototype = new Light(); // 继承抽象类 OffLightState.prototype.buttonWasPressed = function() { console.log("关灯!"); this.light.setState(this.light.weakLight); } /* 弱光 */ WeakLightState.prototype = new Light(); WeakLightState.prototype.buttonWasPressed = function() { console.log("弱光!"); this.light.setState(this.light.strongLight); }; /* 强光 */ StrongLightState.prototype = new Light(); StrongLightState.prototype.buttonWasPressed = function() { console.log("强光!"); this.light.setState(this.light.offLight); };
PS: Additional explanation
The OffLightState, WeakLightState, StrongLightState constructors must be advanced.
new A("a"); var A = function(a) { console.log(a) } new B("b"); function B(b) { console.log(b); }
Function declarations will be hoisted before ordinary variables.
3. Performance optimization points
(1) How to manage the creation and destruction of state objects?
The first is only created when the state object is needed and then destroyed (the state object is relatively large, preferred),
The other is to create all state objects at the beginning and never destroy them (state changes frequently).
(2) Use flyweight mode to share a state object.
4. JavaScript version of state machine
(1) Directly delegate the request to a literal object for execution through the Function.prototype.call method
// 状态机 var FSM = { off: { buttonWasPressed: function() { console.log("关灯"); this.button.innerHTML = "下一次按我是开灯"; // 这是Light上的属性!!! this.currState = FSM.on; // 这是Light上的属性!!! } }, on: { buttonWasPressed: function() { console.log("开灯"); this.button.innerHTML = "下一次按我是关灯"; this.currState = FSM.off; } }, }; var Light = function() { this.currState = FSM.off; // 设置当前状态 this.button = null; }; Light.prototype.init = function() { var button = document.createElement("button"); self = this; button.innerHTML = "已关灯"; this.button = document.body.appendChild(button); this.button.onclick = function() { // 请求委托给FSM状态机 self.currState.buttonWasPressed.call(self); } } var light = new Light(); light.init();
(2)Use delegate function
var delegate = function(client, delegation) { return { buttonWasPressed: function() { return delegation.buttonWasPressed.apply(client, arguments); } }; }; // 状态机 var FSM = { off: { buttonWasPressed: function() { console.log("关灯"); this.button.innerHTML = "下一次按我是开灯"; this.currState = this.onState; } }, on: { buttonWasPressed: function() { console.log("开灯"); this.button.innerHTML = "下一次按我是关灯"; this.currState = this.offState; } }, }; var Light = function() { this.offState = delegate(this, FSM.off); this.onState = delegate(this, FSM.on); this.currState = this.offState; // 设置当前状态 this.button = null; }; Light.prototype.init = function() { var button = document.createElement("button"); self = this; button.innerHTML = "已关灯"; this.button = document.body.appendChild(button); this.button.onclick = function() { // 请求委托给FSM状态机 self.currState.buttonWasPressed(); } } var light = new Light(); light.init();
I hope this article will be helpful to everyone learning JavaScript programming.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.
