---
title: "命令模式（Command）"
author: "ldaolong"
date: "2014-10-15T08:58:48Z"
tags: []
categories: ["非技术"]
slug: "command"
draft: false
lastmod: "2014-10-15T08:58:48Z"
id: 2142604
url: "https://ldaolong.iteye.com/blog/2142604"
---

一、核心思想

命令模式是一个对象行为模式。主要解决在软件构件过程中行为发起者和行为构建者之间的紧耦合的问题。

将一个发起者请求封装成一个对象，将发起者和执行者分开，通过命令的方式来实现。

包含三个类：

请求发起者Invoker：

请求执行者Receiver：

命令MyCommand:

关系图：

todo

 

codes：

[](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 

1. public interface Command {
2. public void execute();
3. }

[](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 

01. public class MyCommand implements Command {
02. private Receiver receiver;
03. public MyCommand(Receiver receiver) {
04. this.receiver = receiver;
05. }
06. @Override
07. public void execute() {
08. receiver.action();
09. }
10. }

[](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 

1. public class Receiver {
2. public void action(){
3. System.out.println("command received!");
4. }
5. }

[](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 

1. public class Invoker {
2. private Command command;
3. public Invoker(Command command) {
4. this.command = command;
5. }
6. public void action(){
7. command.execute();
8. }
9. }

[](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy") 

1. public class Test {
2. public static void main(String\[] args) {
3. Receiver receiver = new Receiver();
4. Command cmd = new MyCommand(receiver);
5. Invoker invoker = new Invoker(cmd);
6. invoker.action();
7. }
8. }

 

二、何时使用

命令模式的目的就是达到命令的发出者和执行者之间解耦

凡是需要将调用和实现分开处理的情况都可以使用命令模式。

 

三、java中的应用

AWT界面事件处理