상태 모드
상태 모드를 사용하면 내부 상태가 변경 될 때 객체가 동작을 변경할 수 있으며 객체가 클래스를 수정하는 것으로 보입니다.
상태 모드의 사용 시나리오는 특히 다음 두 가지 점으로 명확합니다.
1. 객체의 동작은 상태에 따라 달라지며, 실행 시간에 상태에 따라 동작을 바꿔야합니다. (일부 개체에는 일반적으로 여러 상태가 있으며 각 주에서는 현재 상태가 수행 할 수있는 일만 할 수 있지만 다른 상태에서는 할 수있는 일은 아닙니다).
2. 조작에는 다수의 분기 문이 포함되어 있으며,이 분기 문은 객체의 상태에 따라 다릅니다. 상태는 일반적으로 하나 이상의 열거 상수의 표현입니다.
1. 유한 상태 기계
1. 총 상태 수 (상태)는 제한적입니다.
2. 언제든지, 당신은 한 주에만 있습니다.
3. 특정 조건에서는 한 상태에서 다른 상태로 전환됩니다.
일반적인 관행 : 상태를 독립 클래스 (상태 기계)로 캡슐화하고 현재 상태 객체에 요청을 위임합니다. 객체의 내부 상태가 변경되면 다른 동작이 변경됩니다.
2. 성능 최적화 포인트
1. 국가 대상의 생성 및 파괴를 관리하는 방법은 무엇입니까? 첫 번째는 국가 객체가 필요할 때만 상태 객체를 생성하고 파괴하는 것입니다 (상태 객체는 거대하고, 선호), 다른 하나는 처음부터 모든 상태 객체를 만들고 절대 파괴하는 것입니다 (상태 변경).
2. 즐겨 찾기 유안 모드를 사용하여 상태 객체를 공유하십시오.
약간 복잡한 예를 들기 위해, 나는 모든 사람들이 롤 플레잉 게임을했다고 생각하며, 그 캐릭터는 많은 주 (스테이션, 걷기, 달리기, 점프, 쪼그리고 앉는 등)를 가지고 있다고 생각합니다. 다양한 상태 사이의 전환이 지정되며 언제든지 하나의 상태에있을 수 있습니다. 각 상태에서 캐릭터는 현재 상태에서 허용 된 행동 만 수행 할 수 있습니다 (예 : 일반 공격, 다양한 기술 공격, 방어 등).
다음은 내가 쓴 움직이는 공의 예입니다.
<! doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> </title> <cript> wind }}, show2 : {clickbtn : function (key) {change.call (this, key); }}, show3 : {clickbtn : function (key) {change.call (this, key); }}, show4 : {clickbtn : function (key) {change.call (this, key); }}}}; var ball = function () {this.curentState = fsm.show1; this.div = null; }; ball.prototype.init = function () {var self = this; this.div = document.getElementById ( 'go'); document.body.onkeydown = function (event) {var key = event.keyCode; self.curentstate.clickbtn.call (self, key); }}; 함수 변경 (키) {var styles = wind if (key === 40) {top += (top +parseint (styles.height)) <parseint (parentstyles.height)? 10 : 0; this.div.style.top = top+'px'; this.currentState = fsm.show3; } if (key === 38) {top -= (top> 0? 10 : 0); this.div.style.top = top+'px'; this.curentState = fsm.show4; } if (key === 37) {왼쪽 -= (왼쪽> 0? 10 : 0); this.div.style.left = left+'px'; this.curentState = fsm.show1; } if (key === 39) {this.curentState = fsm.show2; 왼쪽 += (왼쪽 +parseint (styles.width)) <parseint (parentstyles.width)? 10 : 0; this.div.style.left = left+'px'; }} var a = new ball (); a.init (); } </script> <tyle> #div {위치 : 절대; 너비 : 80%; 높이 : 80%; 상단 : 0; 하단 : 0; 왼쪽 : 0; 오른쪽 : 0; 마진 : 자동; 국경 : 1px Solid Darkcyan; } #go {위치 : 절대; 너비 : 50px; 높이 : 50px; 왼쪽 : 10px; 상단 : 20px; 테두리 : 1px 단단한 회색; -webkit-border-radius : 50px; -Moz 국경-라디우스 : 50px; Border-Radius : 50px; 배경 이미지 : 방사형 그레이드 (원, 흰색 5%, 검은 색 100%); }.3. State Machine의 JavaScript 버전 (예로서 간단한 스위치 조명을 취함)
1. function.prototype.call 메소드를 통해 문자 그대로의 객체에 요청을 직접 위임합니다.
// state machine var fsm = {off : {buttonwaspressed : function () {console.log ( "downlight"); this.button.innerhtml = "다음을 누르면 빛을 켜고 있습니다."; // 이것은 빛의 속성입니다! ! ! this.currstate = fsm.on; // 이것은 빛의 속성입니다! ! ! }}, on : {buttonwaspressed : function () {console.log ( "light on"); 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 ( "버튼"); self = 이것; button.innerhtml = "light off"; this.button = document.body.appendChild (버튼); this.button.onclick = function () {// fsm state machine self.currstate.buttonwaspressed.call (self)에 위임 요청; }} var light = new light (); light.init ();2. 대의원 기능을 사용하십시오
var delegate = function (client, delegation) {return {buttonwaspressed : function () {return delegation.buttonwaspressed.apply (client, arguments); }};}; // state machine var fsm = {off : {buttonwaspressed : function () {console.log ( "off"); this.button.innerhtml = "다음을 누르면 빛을 켜고 있습니다."; this.currstate = this.onstate; }}, on : {buttonwaspressed : function () {console.log ( "on the light"); 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 ( "버튼"); self = 이것; button.innerhtml = "light off"; this.button = document.body.appendChild (버튼); this.button.onclick = function () {// fsm state machine self.currstate.buttonwaspressed ()에 위임 요청; }} var light = new light (); light.init ();상태 모드와 정책 모드는 매우 유사합니다. 둘 다 일련의 알고리즘이나 동작을 캡슐화합니다. 그들은 모두 캡슐화 된 클래스 (정책 클래스, 상태 기계)에 대한 요청을 위임하기위한 컨텍스트 개체를 가지고 있지만 그들의 의도는 다릅니다.
1. 정책 클래스의 다양한 속성은 동일하게 평행하며 그것들 사이에는 연결이 없습니다.
2. 상태 기계의 다양한 상태간에 상호 전환이 있으며 지정되어 있습니다.
참고 문헌 : "JavaScript Pattern" "JavaScript 디자인 패턴 및 개발 실습"
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.