码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式总结5--命令模式 commend pattern

时间:2015-01-15 20:10:53      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

命令模式把发出命令的责任和执行命令
的责任分割开,委派给不同的对象。就像我们去餐厅,点菜是找服务员,然后服务员去让厨师做菜
而不是我们直接找厨师做菜

public interface Commend {
    
    public void execute();
}
public class Remoter {
    
    public void click(Commend cmd){
        cmd.execute();
    }
}
public class OpenLightCommend  implements Commend{

    private Light light;
    
    public OpenLightCommend(Light light){
        this.light = light;
    }
    @Override
    public void execute() {
        
        light.open();
        
    }

}

测试

 

public class test {
    
    public static void main(String[] args) {
        /*命令的执行者light和命令的发出者remoter是分开的,靠着OpenLightCommend
            连接*/
        Light light = new Light();
        
        OpenLightCommend olc = new OpenLightCommend(light);
        Remoter r = new Remoter();
        r.click(olc);
    }
}

 

===================================

===================================

宏命令:宏命令是命令的一种简单延伸,允许调用多个命令

public class MarcoCommend implements Commend{

    private Commend[] cmds;
    public MarcoCommend(Commend... cmds){
        this.cmds = cmds;
    }
    
    @Override
    public void execute() {
        for(Commend c : cmds){
            c.execute();
        }
        
    }

}
public class test {
    
    public static void main(String[] args) {
        
        Light light = new Light();
        
        OpenLightCommend olc = new OpenLightCommend(light);
        CloseLightCommend clc = new CloseLightCommend(light);
        MarcoCommend mc = new MarcoCommend(olc,clc);
        
        
        Remoter r = new Remoter();
        r.click(mc);
    }
}

 

设计模式总结5--命令模式 commend pattern

标签:

原文地址:http://www.cnblogs.com/itliucheng/p/4227070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!