---
title: "Command模式"
author: "Jameslyy"
date: "2007-07-25T17:18:50Z"
tags: []
slug: "command"
draft: false
lastmod: "2007-07-25T17:18:50Z"
id: 105446
url: "https://jamesblog.iteye.com/blog/105446"
---

Command模式，对功能的调用和功能的实现进行解藕。功能的调用者不用知道具体的功能是怎样实现的，使用了接口，具有很大的灵活性，使代码稳健、可维护、可复用。

下面是一个简单的例子，首先建立一个接口ICommand，

public interface ICommand {  
       void execue();  
}

然后是两个实现了这个接口和具体功能的实用类：

public class Printer implements ICommand {  
     public void execue() {  
          System.out.println("printed!");  
     }  
}

public class FileOpener implements ICommand {  
      public void execue() {  
          System.out.println("Open file");  
      }  
}

在下面的这个类中实现了命令模式：

public class SystemFunction {  
       private List&lt;ICommand&gt; cmds = new ArrayList&lt;ICommand&gt;();  
       public SystemFunction() {  
             cmds.add(new FileOpener());  
             cmds.add(new Printer());  
       }  
       public void doWork() {  
             // TODO Auto-generated method stub  
             for(ICommand cmd:cmds) {  
                   cmd.execue();  
             }  
       }  
       public static void main(String\[] args) {  
             SystemFunction cmd = new SystemFunction();  
             cmd.doWork();  
       }  
}

使用List存储具体的命令对象，由于实现了接口，所以能够以接口来引用具体的对象，这样就体现了解藕和灵活性。

通过以上简单的代码演示，应该可以对Command模式有一个大概的认识，为实际的开发提供更多的思路。