State

State

Состояние (англ. State) — шаблон проектирования. Используется в тех случаях, когда во время выполнения программы объект должен менять свое поведение в зависимости от своего состояния.

Паттерн состоит из 3 блоков:

Widget — класс, объекты которого должны менять свое поведение в зависимости от состояния.

IState — интерфейс, который должно реализовать каждое из конкретных состояний. Через этот интерфейс объект Widget взаимодействует с состоянием, делегируя ему вызовы методов. Интерфейс должен содержать средства для обратной связи с объектом, поведение которого нужно изменить. Для этого используется событие (паттерн Publisher — Subscriber). Это необходимо для того, чтобы в процессе выполнения программы заменять объект состояния при появлении событий. Возможны случаи, когда сам Widget периодически опрашивает объект состояние на наличие перехода.

StateA … StateZ — классы конкретных состояний. Должны содержать информацию о том, при каких условиях и в какие состояния может переходить объект из текущего состояния. Например, из StateA объект может переходить в состояние StateB и StateC, а из StateB — обратно в StateA и так далее. Объект одного из них должен содержать Widget при создании.

Примеры

Javascript

Пример со сменой состояний из State.

// "интерфейс" State
 
	function State() {
		this.someMethod = function() { };
		this.nextState = function() { };
	}
 
 
// реализация State
 
	// первое состояние
	function StateA(widjet) {
		var dublicate = this; // ссылка на инстанцирующийся объект (т.к. this может меняться)
 
		this.someMethod = function() {
			alert("StateA.someMethod");
			dublicate.nextState();
		};
		this.nextState = function() {
			alert("StateA > StateB");
			widjet.onNextState( new StateB(widjet) );
		};
	}
	StateA.prototype = new State();
	StateA.prototype.constructor = StateA;
 
	// второе состояние
	function StateB(widjet) {
		var dublicate = this;
 
		this.someMethod = function() {
			alert("StateB.someMethod");
			dublicate.nextState();
		};
		this.nextState = function() {
			alert("StateB > StateA");
			widjet.onNextState( new StateA(widjet) );
		};
	}
	StateB.prototype = new State();
	StateB.prototype.constructor = StateB;
 
 
// "интерфейс" Widget
 
	function Widget() {
		this.someMethod = function() { };
		this.onNextState = function(state) { };
	}
 
 
// реализация Widget
 
	function Widget1() {
		var state = new StateA(this);
 
		this.someMethod = function() {
			state.someMethod();
		};
		this.onNextState = function(newState) {
			state = newState;
		};
	}
	Widget1.prototype = new Widget();
	Widget1.prototype.constructor = Widget1;
 
 
// использование
 
var widget = new Widget1();
widget.someMethod(); // StateA.someMethod
                     // StateA > StateB
widget.someMethod(); // StateB.someMethod
                     // StateB > StateA

Смена состояний с помощью вызова метода у Widget (из англоязычной версии статьи).

// "интерфейс" State
 
	function AbstractTool() {
		this.moveTo = function(x, y) { };
		this.mouseDown = function(x, y) { };
		this.mouseUp = function(x, y) { };
	}
 
 
// реализация State
 
	// инструмент "карандаш"
	function PenTool(widjet) {
		var dublicate = this;    // ссылка на инстанцирующийся объект (т.к. this может меняться)
		var mouseIsDown = false; // кнопка мыши сейчас не нажата
		var lastCoords = [];     // прошлые координаты курсора мыши
 
		this.moveTo = function(x, y) { 
			if (mouseIsDown && lastCoords.length) {
				drawLine(lastCoords, [x, y]);
			}
			lastCoords = [x, y];
		};
		this.mouseDown = function(x, y) {
			mouseIsDown = true;
			lastCoords = [x, y];
		};
		this.mouseUp = function(x, y) { 
			mouseIsDown = false;
		};
 
		function drawLine(coords1, coords2) {
			alert("drawLine: ["+ coords1[0] +", "+ coords1[1] +"] - ["+ coords2[0] +", "+ coords2[1] +"]");
		}
 
	}
	PenTool.prototype = new AbstractTool();
	PenTool.prototype.constructor = PenTool;
 
	// инструмент "выделение области"
	function SelectionTool(widget) {
		var dublicate = this;    // ссылка на инстанцирующийся объект (т.к. this может меняться)
		var mouseIsDown = false; // кнопка мыши сейчас не нажата
		var startCoords = [];    // координаты курсора мыши при нажатии на кнопку
 
		this.moveTo = function(x, y) { 
			if (mouseIsDown) {
				setSelection(startCoords, [x, y]);
			}
		};
		this.mouseDown = function(x, y) {
			startCoords = [x, y];
			mouseIsDown = true;
		};
		this.mouseUp = function(x, y) { 
			mouseIsDown = false;
		};
 
		function setSelection(coords1, coords2) {
			alert("setSelection: ["+ coords1[0] +", "+ coords1[1] +"] - ["+ coords2[0] +", "+ coords2[1] +"]");
		}
	};
	SelectionTool.prototype = new AbstractTool();
	SelectionTool.prototype.constructor = SelectionTool;
 
 
// реализация Widget
 
	function DrawingController() {
		var currentTool = new SelectionTool(); // активный инструмент
 
		this.moveTo = function(x, y) {
			currentTool.moveTo(x, y);
		};
		this.mouseDown = function(x, y) { 
			currentTool.mouseDown(x, y);
		};
		this.mouseUp = function(x, y) { 
			currentTool.mouseUp(x, y);
		};
 
		this.selectPenTool = function() {
			// выбираем инструмент "выделение области" 
			currentTool = new PenTool();
		};
		this.selectSelectionTool = function() {
			// выбираем инструмент "карандаш" 
			currentTool = new SelectionTool();
		};
	}
 
var widget = new DrawingController();
 
widget.mouseDown(1, 1);
widget.moveTo(1, 2); // setSelection: [1, 1] - [1, 2]
widget.moveTo(1, 3); // setSelection: [1, 1] - [1, 3]
widget.mouseUp(1, 3);
widget.moveTo(1, 4);
 
widget.selectPenTool();
widget.mouseDown(1, 1);
widget.moveTo(1, 2); // drawLine: [1, 1] - [1, 2]
widget.moveTo(1, 3); // drawLine: [1, 2] - [1, 3]
widget.mouseUp(1, 3);
widget.moveTo(1, 4);



Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Полезное


Смотреть что такое "State" в других словарях:

  • state — state, the state The state is a distinct set of institutions that has the authority to make the rules which govern society . It has, in the words of Max Weber, a ‘monopoly on legitimate violence’ within a specific territory. Hence, the state… …   Dictionary of sociology

  • State — (st[=a]t), n. [OE. stat, OF. estat, F. [ e]tat, fr. L. status a standing, position, fr. stare, statum, to stand. See {Stand}, and cf. {Estate}, {Status}.] 1. The circumstances or condition of a being or thing at any given time. [1913 Webster]… …   The Collaborative International Dictionary of English

  • state — [steɪt] noun 1. [countable usually singular] the condition that someone or something is in at a particular time: • The property market is in a poor state. • I personally think the economy is in a worse state than the Government has been admitting …   Financial and business terms

  • state — n often attrib 1 a: a politically organized body of people usu. occupying a definite territory; esp: one that is sovereign b: the political organization that has supreme civil authority and political power and serves as the basis of government… …   Law dictionary

  • state — [stāt] n. [ME < OFr & L: OFr estat < L status, state, position, standing < pp. of stare, to STAND] 1. a set of circumstances or attributes characterizing a person or thing at a given time; way or form of being; condition [a state of… …   English World dictionary

  • state — state; state·hood; state·less; state·less·ness; state·let; state·li·ly; state·li·ness; state·sid·er; su·per·state; tung·state; un·state; mi·cro·state; mini·state; in·ter·state; state·ly; state·ment; …   English syllables

  • state — ► NOUN 1) the condition of someone or something at a particular time. 2) a nation or territory considered as an organized political community under one government. 3) a community or area forming part of a federal republic. 4) (the States) the… …   English terms dictionary

  • state — It is usual to spell it with a capital initial letter when it refers to political entities, either nations (The State of Israel / a State visit), or parts of a federal nation (the State of Virginia / crossing the State border), and when it means… …   Modern English usage

  • State — State, v. t. [imp. & p. p. {Stated}; p. pr. & vb. n. {Stating}.] 1. To set; to settle; to establish. [R.] [1913 Webster] I myself, though meanest stated, And in court now almost hated. Wither. [1913 Webster] Who calls the council, states the… …   The Collaborative International Dictionary of English

  • state — [n1] condition or mode of being accompaniment, attitude, capacity, case, category, chances, character, circumstance, circumstances, contingency, element, environment, essential, estate, event, eventuality, fix, footing, form, frame of mind, humor …   New thesaurus

  • State — (st[=a]t), a. 1. Stately. [Obs.] Spenser. [1913 Webster] 2. Belonging to the state, or body politic; public. [1913 Webster] …   The Collaborative International Dictionary of English


Поделиться ссылкой на выделенное

Прямая ссылка:
Нажмите правой клавишей мыши и выберите «Копировать ссылку»