• java设计模式(六) 命令模式


    【命令模式】将”请求“封装成对象,以便使用不同的请求,队列或者日志来参数化其他对象,命令模式也支持可撤销的操作。

    1,定义命令接口

    package com.pattern.command;
    
    public interface Command {
    	
    	public void execute();
    	
    }


    2,接口的实现类

    package com.pattern.command;
    
    public class LightOnCommand implements Command{
    	Light light;
    	
    	public LightOnCommand(Light light){
    		this.light = light;
    	}
    	
    	/** 
    	 * @see com.pattern.command.Command#execute()
    	 */
    	@Override
    	public void execute() {
    		light.on();
    	}
    
    }

    3,命令的具体执行者

    package com.pattern.command;
    
    public class Light {
    	
    	public void on(){
    		System.out.println("turn on the light!");
    	}
    
    }


    4,控制器类

    package com.pattern.command;
    
    public class SimpleRemoteControl {
    	
    	Command slot;
    	
    	public SimpleRemoteControl(){}
    	
    	public void setCommand(Command command){
    		slot = command;
    	}
    	
    	public void buttonWasPressed(){
    		slot.execute();
    	}
    }

    5,测试类

    package com.pattern.command;
    
    public class RemoteControlTest {
    	
    	public static void main(String[] args) {
    		SimpleRemoteControl remote = new SimpleRemoteControl();
    		Light light = new Light();
    		LightOnCommand lightOn = new LightOnCommand(light);
    		
    		remote.setCommand(lightOn);
    		remote.buttonWasPressed();
    	}
    }
    


    输出结果:

    turn on the light!


     

  • 相关阅读:
    cell list of blocks physical read等待事件
    cell manager discovering disks等待事件
    OOP
    静态网页与动态网页的区别
    一个HTTP请求的详细过程
    PING 确认网络连接情况
    软件开发模型
    搭建网站的全套流程
    Design Diagram
    网络基础
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986816.html
Copyright © 2020-2023  润新知