티스토리 뷰

웹개발/Javascript

Command 패턴 정리

yaku 2011. 10. 18. 17:28
* 요청 내역을 객체로 캡슐화하여 클라이언트를 서로 다른 요청 내역에 따라 매개 변수화 할 수 있습니다.
  요청을 큐에 저장하거나 로그로 기록 할 수 도 있고 작업취소 기능을 지원 할 수 도 있습니다.

var oSimpleRemote = new SimpleRemoteControl();
var oLight = new Light();
var oLightCommand = new LightOnCommand(oLight);

oSimpleRemote.setCommand(oLightCommand);
oSimpleRemote.buttonWasPressed();
oSimpleRemote.buttonUndoWasPressed();
	

// Light

var Light = function(){
	this.bOn = false;
};
Light.prototype.on = function(){
	this.bOn = true;
	console.log("Light is on");
};
Light.prototype.off = function(){
	this.bOn = false;
	console.log("Light is off");
};

// Command 

var Command = function(){

};
Command.prototype.execute = function(){
	throw new Error("This method must be overwritten!");
};
Command.prototype.undo = function(){
	throw new Error("This method must be overwritten!");
};

// LightOnCommand 

var LightOnCommand = function(oLight){
	Command.apply(this);
	this.oLight = oLight;
};
LightOnCommand.prototype = new Command();
LightOnCommand.prototype.execute = function(){
	this.oLight.on();
};
LightOnCommand.prototype.undo = function(){
	this.oLight.off();
};


//  SimpleRemoteControl
var SimpleRemoteControl = function(){
	this.oCommand = null;
};
SimpleRemoteControl.prototype.setCommand = function(oCommand){
	this.oCommand = oCommand;
};
SimpleRemoteControl.prototype.buttonWasPressed = function(){
	this.oCommand.execute();
};
SimpleRemoteControl.prototype.buttonUndoWasPressed = function(){
	this.oCommand.undo();
};


댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함