命令模式

Command接口

public interface Command
{
	//接口里定义process方法用于封装“处理行为”
	void process(int [] target);
}

处理数组的处理类ProcessArray

public class ProcessArray
{
	public void procsess(int[] target ,Command cmd)
	{
		cmd.process(target);
	}
}

Command接口的两个实现类

public class AddCommand implements Command
{
	@Override
	public void process(int[] target)
	{
		int sum =0;
		for(int tmp:target)
		{
			sum+=tmp;
		}
		System.out.println("数组元素的总和是:”+sum);
	}
}
public class PrintCommand implements Command
{
	@Override
	public void process(int[] target)
	{
		for(int tmp:target)
		{
			System.out.println("迭代输出数组元素:"+tmp);
		}
	}
}

CommandTest

public class CommandTest
{
	public static void main(String[]args)
	{
		ProcessArray pa = new ProcessArray ;
		int [] target = {1,3,5,7,9};
		//第一次处理数组,具体处理行为取决于PrintCommand
		pa.process( target , new PrintCommand());
		//第一次处理数组,具体处理行为取决于AddCommand 
		pa.process( target , new AddCommand());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值