【设计模式】【命令模式】


/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> 
 * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
public class ProcessArray
{
	//定义一个each()方法,用于处理数组,
	public void each(int[] target , Command cmd) 
	{
		cmd.process(target);
	}
}




/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> 
 * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
public interface Command
{
	//接口里定义的process方法用于封装“处理行为”
	void process(int[] target);
}



/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> 
 * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
public class CommandTest
{
	public static void main(String[] args) 
	{
		ProcessArray pa = new ProcessArray();
		int[] target = {3, -4, 6, 4};
		//第一次处理数组,具体处理行为取决于Command对象
		pa.each(target , new Command()
		{
			//重写process()方法,决定具体的处理行为
			public void process(int[] target)
			{
				for (int tmp : target )
				{
					System.out.println("迭代输出目标数组的元素:" + tmp);
				}
			}
		});
		System.out.println("------------------");
		//第二次处理数组,具体处理行为取决于Command对象
		pa.each(target , new Command()
		{
			//重写process方法,决定具体的处理行为
			public void process(int[] target)
			{
				int sum = 0;
				for (int tmp : target )
				{
					sum += tmp;			
				}
				System.out.println("数组元素的总和是:" + sum);
			}
		});
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值