当前页面: 开发资料首页 → J2SE 专题 → J2SE 5.0 Generic应用一:类型安全的functor
摘要: J2SE 5.0 Generic应用一:类型安全的functor
函数式编程是非常常用和非常重要的一种编程范式,有的语言直接提供支持,C++则通过()运算符重载和模板提供了还算灵活的支持,而Java中的函数式编程则由于语言本身的局限没有得到广泛应用,Apache Commons Functor 项目是一个正在开发中的函数式编程库,但目前看来并不是类型安全的;J2SE 5.0提供了有限的generic能力,除了用于Collection之外,类型安全的functor也是其用武之地,已有一个开源项目Generic Algorithms for Java开始了这方面的工作
一元函数、谓词、过程
public interface UnaryFunction
R evaluate(P obj);
}
public interface UnaryPredicate
boolean test(T obj);
}
public interface UnaryProcedure
void run(T obj);
}
二元函数、谓词、过程
public interface BinaryFunction
R evaluate(T left, S right);
}
public interface BinaryPredicate
boolean test(T left, S right);
}
public interface BinaryProcedure
void run(T left, S right);
}
特化一:过滤
public interface Filter
}
几个示例算法:transform、select、foreach
public static
List
for(Source item : source){
result.add(transformer.evaluate(item));
}
return result;
}
public static
List
for(T item : source){
if(selector.test(item)){
result.add(item);
}
}
return result;
}
public static
for(T item : source){
procedure.run(item);
}
}
几个composite:And、Or、Not
public class And
private UnaryPredicate
public And(UnaryPredicate
this.predicates = predicates;
}
public boolean test(T obj) {
for(UnaryPredicate
if( !predicate.test(obj) ){
return false;
}
}
return true;
}
public static
return new And
}
}
public class Or
private UnaryPredicate
public Or(UnaryPredicate
this.predicates = predicates;
}
public boolean test(T obj) {
for(UnaryPredicate
if( predicate.test(obj) ){
return true;
}
}
return false;
}
public static
return new Or
}
}
public class Not
private UnaryPredicate
public Not(UnaryPredicate
this.predicate = predicate;
}
public boolean test(T obj) {
return !predicate.test(obj);
}
public static
return new Not
}
}