zoukankan      html  css  js  c++  java
  • 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!


     

  • 相关阅读:
    DataPager 分页样式(css)
    Mysql日志详解
    Oracle 优化器
    [oracle]对象统计数据
    [oracle] analyze 和dbms_stats 的区别
    增加SAP HEAP大小
    Problems with SYSDBA/SYSOPER/INTERNAL connect
    Physical Standby Switchover_status Showing Not Allowed
    REHL8 oracle 19C RAC安装中的坑
    REHL8 oracle 19C RAC安装四(数据库创建)
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986816.html
Copyright © 2011-2022 走看看