接口(命令模式):

//-定义接口
interface Command{
	void process(int[] array);
}

//-实现类:1 
class PrintCommand implements Command{
	public void process(int[] array){
		for(int arr:array){
			System.out.println("数组的元素分别为:"+arr);
		}
	}
}

//-实现类:2
class AddCommand implements Command{
	public void process(int[] array){
		int sum=0;
		for(int arr:array){
			sum+=arr;
		}
		System.out.println("数组的总和为"+sum);
	}
}

//-定义与实现类分离的类,通过多态的方式,调用实现类的方法
class ProcessComm{
	public void process(int[] array,Command com){
		com.process(array);
	}
}

//-调用与实现类分离的类,通过多态方式,获取接口类型的 不同实现类实例
//-以后若要对实现类更换或修改,直接重新定义一个实现类,并在该类指向该实现类即可,不需要动过去的实现类
//-通过接口,彻底实现规范与实现类的分离
public class CommandTest{
	public static void main(String[] args){
		int[] array={3,4,6,10};
		ProcessComm pro=new ProcessComm();
		pro.process(array,new PrintCommand());
		pro.process(array,new AddCommand());
	}
}

 

posted on 2018-01-13 13:25  不丶懂  阅读(575)  评论(0编辑  收藏  举报

导航