命令模式


场景:  需要处理一组数据,但是不知道该使用哪种处理方式,只有在处理时才知道。

其实就是想要把运行的代码作为参数传递到某个函数中去,来处理某些数据。

类似于C程序中把一个函数类型作为参数。

在java中使用接口来实现这一功能。

定义command接口

public interface Command
{
	void process(int[] target);//用于封装“处理行为”
}


实现Command接口

public class AddCommand implements Command
{
	public void process(int[] target)
	{
		int sum = 0;
		for(int tmp : target)
			sum += tmp;
		System.out.println("sum is " + sum);
	}
}

 

public class PrintCommand implements Command
{
	public void process(int[] target)
	{
		for(int tmp : target)
		{
			System.out.println("printCommand :" + tmp);
		}
	}
}

 

处理类,处理函数有一个接口参数。

 

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


 

调用处理类

 

public class TestCommand
{
	public static void main(String[] args)
	{
		int[] array = new int[] {1, 2, 3, 4, 5, 6, 7};
		ProcessArray pa = new ProcessArray();
		pa.process(array, new AddCommand());
		pa.process(array, new PrintCommand());
	}
}



 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值