silvermyth

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  1 随笔 :: 12 文章 :: 1 评论 :: 0 Trackbacks
命令模式是一种应用比较广泛的模式,它的最核心思想是命令的接受者和执行者独立,从而大大降低了代码的耦合度。举个例子,我家小朋友晚上睡觉前对妈妈(命令接受者)说第二天早上要吃蒸鸡蛋羹(发送命令);对于小朋友来说最重要的就是第二天早上一醒来看到桌上有一碗鸡蛋羹,而她根本不关心这是谁做的(谁执行的相关命令),妈妈亲自做的也好,爸爸爱心奉献的也好,饭店里买的也不是不可以。
在适配器模式中我们提到,Garin新交了个女朋友,他每天都会收到如下命令:
1 public interface Command {
2     public void execute();
3 }
其中一部分是做饭,一部分是洗衣服;Garin必须亲自完成吗,不一定:
 1 public class CookCommand implements GirlFriendCommand {
 2 
 3     private String mealName = null;
 4     
 5     public CookCommand(String mealName) {
 6         super();
 7         this.mealName = mealName;
 8     }
 9 
10     private MealSupplier mealSupplier = null;
11     
12     public void setMealSupplier(MealSupplier mealSupplier) {
13         this.mealSupplier = mealSupplier;
14     }
15 
16     @Override
17     public void execute() {
18         mealSupplier.cook(mealName);
19     }
20 
21 }
真正完成做饭的是一个抽象的MealSupplier.
1 public interface MealSupplier {
2     public void cook(String name);
3 }
它可能代表的是一个饭店:
 1 public class Restaurant implements MealSupplier{
 2     
 3     public Restaurant() {
 4         super();
 5     }
 6 
 7     @Override
 8     public void cook(String name) {
 9         System.out.println("饭店烧好了"+name);
10     }
11     
12 }
同样的,真正洗衣服的是抽象的CanWash.
 1 public class WashCommand implements GirlFriendCommand {
 2 
 3     private CanWash wash = null;
 4     
 5     public void setWash(CanWash wash) {
 6         this.wash = wash;
 7     }
 8 
 9     @Override
10     public void execute() {
11         if(wash != null){
12             wash.washClothes();
13         }
14     }
15 
16 }
它代表的可能是洗衣机:
1 public interface CanWash {
2     public void washClothes();
3 }

1 public class WashingMachine implements CanWash {
2 
3     @Override
4     public void washClothes() {
5         System.out.println("洗衣机洗好了衣服");
6     }
7 
8 }
Garin要做的就是坐等命令,如何执行完全不管:
 1 public class GirlFriendCommandTest {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         BoyFriend bf = new BoyFriend("Garin");
 8         
 9         bf.addCommand(new CookCommand("鱼香肉丝"));
10         bf.addCommand(new WashCommand());
11         bf.action();
12     }
13 
14 }
执行完命令后效果如下:
Garin开始执行命令
饭店烧好了鱼香肉丝
洗衣机洗好了衣服
posted on 2015-07-28 21:22 Gavin Li 阅读(218) 评论(1)  编辑  收藏 所属分类: 设计模式

评论

# re: 闲话Java设计模式三:命令模式 2015-08-04 08:58 Philip
BoyFriend怎么没有定义啊? 不好意思  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: