---
title: "设计模式之命令模式"
author: "hwaspf"
date: "2009-09-28T12:06:37Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-09-28T14:41:16Z"
id: 479316
url: "https://hwaspf.iteye.com/blog/479316"
---

命令模式将“请求”封装成对象，实现请求调用者和请求接收者之间的解耦。


```java
public class Light {
	String location = "";

	public Light(String location) {
		this.location = location;
	}

	public void on() {
		System.out.println(location + " light is on");
	}

	public void off() {
		System.out.println(location + " light is off");
	}
}
```



```java
public interface Command {
	public void execute();
}

```



```java
public class LightOnCommand implements Command {
	Light light;
 
	public LightOnCommand(Light light) {
		this.light = light;
	}
 
	public void execute() {
		light.on();
	}
 
	public void undo() {
		light.off();
	}
}
```



```java
public class LightOffCommand implements Command {
	Light light;
 
	public LightOffCommand(Light light) {
		this.light = light;
	}
 
	public void execute() {
		light.off();
	}
 
	public void undo() {
		light.on();
	}
}
```



```java
public class SimpleRemoteControl {
	Command slot;
 
	public SimpleRemoteControl() {}
 
	public void setCommand(Command command) {
		slot = command;
	}
 
	public void buttonWasPressed() {
		slot.execute();
	}
         
    public void undoButtonWasPushed(){
        slot.undo();
    }
      
}

```



```java
public class RemoteControlTest {
	public static void main(String[] args) {
		SimpleRemoteControl remote = new SimpleRemoteControl();
		Light light = new Light("Living room");
		LightOnCommand lightOn = new LightOnCommand(light);
        LightOffCommand lightOff = new LightOffCommand(light);
		 
		remote.setCommand(lightOn);
		remote.buttonWasPressed();
        remote.undoButtonWasPushed();
		remote.setCommand(garageOpen);
		remote.buttonWasPressed();
    }
}
```