java设计模式-命令模式

本文介绍了Java中的命令模式,这是一种数据驱动的设计模式,用于降低系统耦合度。文章通过代码示例展示了如何实现命令接口、调用者、具体命令类及其应用。同时,讨论了命令模式的优点(如易扩展)和可能的缺点,以及适用场景,如GUI按钮和命令行操作。
摘要由CSDN通过智能技术生成
package com.hcmony.command;

/**
 * <h3>Shenjue.java基本描述</h3>
 * <p></p>
 *
 * @author hcmony
 * @since V1.0.0, 2018/04/09 17:18
 */
public interface CommandInteface {
	public void exe();
}

package com.hcmony.command;

/**
 * <h3>Shenjue.java基本描述</h3>
 * <p></p>
 *
 * @author hcmony
 * @since V1.0.0, 2018/04/09 17:20
 */
public class Invoker {
	private CommandInteface inteface;
	public Invoker(CommandInteface inteface){
		this.inteface=inteface;
	}
	public void action(){
		inteface.exe();
	}

	public static void main(String[] args) {
		Command command = new Command();
		CommandInteface inteface = new MyCommand(command);
		Invoker invoker = new Invoker(inteface);
		invoker.action();
	}
}

package com.hcmony.command;

/**
 * <h3>Shenjue.java基本描述</h3>
 * <p></p>
 *
 * @author hcmony
 * @since V1.0.0, 2018/04/03 20:26
 */
public class Command {
	public void action(){
		System.out.println("Command    action ");
	}
}

package com.hcmony.command;

/**
 * <h3>命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。
 * 		请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
 * </h3>
 * <p>	优点: 1、降低了系统耦合度。 2、新的命令可以很容易添加到系统中去。
 		缺点:使用命令模式可能会导致某些系统有过多的具体命令类。
 		使用场景:认为是命令的地方都可以使用命令模式,比如: 1、GUI 中每一个按钮都是一条命令。 2、模拟 CMD。
 		注意事项:系统需要支持命令的撤销(Undo)操作和恢复(Redo)操作,也可以考虑使用命令模式,见命令模式的扩展。
 </p>
 *
 * @author hcmony
 * @since V1.0.0, 2018/04/09 17:18
 */
public class MyCommand implements CommandInteface {
	private Command command;

	public MyCommand(Command command){
		this.command = command;
	}
	@Override
	public void exe() {
		command.action();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值