策略的設計模式
java中的設備模式,用一句話來說就是利用多態的函數類來實現設計的模式
//定義接口
interface Combiner<T>
{
T combine(T x,T y);
}
//整個實現過程是這樣的:
首先定義一個嵌套類(static內部類):IntegerAdder類,像是一個函數類,他實現了combiner接口中的combine()方法;然後定義一個reduce()方法,在main()函數值中調用,然後將IntegerAdder函數類作爲一個對象傳進去,在reduce方法中由於多態,其中的combiner.combine()將會調用IntegerAdder類內定義的combine();
class Functional
{
public static<T> Treduce(Iterable<T> seq,Combiner<T> combiner)
{
Iterator<T> it=seq.iterator();
if(it.hasNext()){
T result=it.next();
while(it.hasNext()){
result=combiner.combine(result,it.next());
}
return result;
}
return null;
}
static classIntegerAdder implements Combiner<Integer>
{
public Integer combine(Integerx,Integer y)
{
return x+y;
}
}
public staticvoid main(String[] args)
{
List<Integer>li=Arrays.asList(1,2,3,4,5,6,7);
Integer result=reduce(li,newIntegerAdder());
System.out.println(result);
}
}