Wednesday, October 20, 2010

Command. Loại: Behavioral. Độ khó: Trung bình

Command nghĩa là ra lệnh. Sĩ quan chỉ huy gọi là commander, người này không làm mà chỉ ra lệnh cho người khác làm. Như vậy, phải có người nhận lệnh và thi hành lệnh (receiver).

Bây giờ ta lấy ví dụ sau. Bóng đèn Light có 2 phương thức switchOn và switchOff.

class Light()
{
void switchOn(){
System.out.println("Switch light on");
}

void switchOff(){
System.out.println("Switch light off");
}
}

Tuy vậy, để giống trong quân đội, ta làm 1 interface tên là Command không trực tiếp tắt bật đèn mà chỉ ra lệnh cho bóng đèn bật tắt.

interface Command(){
void execute();
}

Ta hiện thực interface này bằng 2 class: CommandOff và CommandOn

class CommandOff(){
Light light;
public CommandOff(Light light){
this.light = light;
}

public void execute(){
light.switchOff();
}
}


class CommandOn(){
Light light;
public CommandOn(Light light){
this.light = light;
}

public void execute(){
light.switchOn();
}
}

Bây giờ đã đóng gói các command này vào trong 1 bộ điều khiển gọi là Remote Control

class RemoteControl(){

private Command command;

public setCommand(Command command){
this.command = command;
}

public void pressButton(){
command.execute();
}

Sử dụng remote control này như sau:
public static void main(String[] args){

RemoteControl rc = new RemoteControl();

Light light = new Light();
Command c1 = new CommandOff(light);
Command c2 = new CommandOn(light);

rc.setCommand(c1);
rc.pressButton();

rc.setCommand(c2);
rc.pressButton();

}

Như vậy, ta có thể truyền bất cứ command nào vào Remote control để yêu cầu thực hiện. Khi đó, yêu cầu thực hiện đã được đóng gói vào trong 1 object như mô tả trong GoF book:

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations


No comments:

Post a Comment