---
title: "设计模式——命令模式"
author: "剑锋凛冽"
date: "2012-11-22T13:57:00Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-11-22T13:57:00Z"
id: 1733225
url: "https://swordboy007.iteye.com/blog/1733225"
---

命令模式的本质是将对同一对象的不同操作进行不同封装，但同时又通过接口，提供给调用者一个统一的使用方式，从事隔离调用者对对象操作的复杂逻辑处理。在命令中可以又可以通过接口或类来通过自身持有的接受者来讲操作转移到接受者来负责具体的操作实现。

参见如下代码

```
package pattern;

public class CommandDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] target={1,2,3,4,5};
		
		Executor.executeCommand(target,new AddCommand());
		Executor.executeCommand(target, new StringCommand());
		
		Executor.executeAction(new AddCommand(), new Receiver());
		Executor.executeAction(new StringCommand(), new Receiver());
		
	}

}
class Executor{
	
	public static void executeCommand(int[] target,Command command){
		command.process(target);
	}
	
	public static void executeAction(Command command,Receiver receiver){
		command.processAction(receiver);
	}
}
interface Command{
	
	void process(int[] target);
	
	void processAction(Receiver receiver);
	
}
class Receiver{
	
	public void doAction(String action){
		System.out.println("执行操作"+action);
	}
}
class AddCommand implements Command{

	@Override
	public void process(int[] target) {
		// TODO Auto-generated method stub
		int sum=0;
		for(int num:target){
			sum+=num;
		}
		System.out.println("AddCommand执行结果"+sum);
	}

	@Override
	public void processAction(Receiver receiver) {
		// TODO Auto-generated method stub
		System.out.println("AddCommand发出命令");
		receiver.doAction("add");
		System.out.println("AddCommand执行完成");
	}
	
}
class StringCommand implements Command{

	@Override
	public void process(int[] target) {
		// TODO Auto-generated method stub
		StringBuilder sb=new StringBuilder();
		for(int num:target){
			sb.append(num);
		}
		System.out.println("StringCommand执行结果"+sb.toString());
	}

	@Override
	public void processAction(Receiver receiver) {
		// TODO Auto-generated method stub
		System.out.println("StringCommand发出命令");
		receiver.doAction("string");
		System.out.println("StringCommand执行完成");
	}
	
}
```