站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题J2SE 5.0 Generic应用一:类型安全的functor

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 extends UnaryFunction{
}

public static List transform(Collection source, UnaryFunction transformer){
List result = new ArrayList();
for(Source item : source){
result.add(transformer.evaluate(item));
}
return result;
}

public static List select(Collection source, UnaryPredicate selector){
List result = new ArrayList();
for(T item : source){
if(selector.test(item)){
result.add(item);
}
}
return result;
}

public static void foreach(Collection source, UnaryProcedure procedure){
for(T item : source){
procedure.run(item);
}
}

public class And implements UnaryPredicate, Serializable{
private UnaryPredicate[] predicates;
public And(UnaryPredicate... predicates){
this.predicates = predicates;
}
public boolean test(T obj) {
for(UnaryPredicate predicate : predicates){
if( !predicate.test(obj) ){
return false;
}
}
return true;
}
public static And and(UnaryPredicate... predicates){
return new And(predicates);
}
}

public class Or implements UnaryPredicate, Serializable{
private UnaryPredicate[] predicates;
public Or(UnaryPredicate... predicates){
this.predicates = predicates;
}
public boolean test(T obj) {
for(UnaryPredicate predicate : predicates){
if( predicate.test(obj) ){
return true;
}
}
return false;
}
public static Or or(UnaryPredicate... predicates){
return new Or(predicates);
}
}

public class Not implements UnaryPredicate, Serializable{
private UnaryPredicate predicate;
public Not(UnaryPredicate predicate){
this.predicate = predicate;
}
public boolean test(T obj) {
return !predicate.test(obj);
}
public static Not not(UnaryPredicate predicate){
return new Not(predicate);
}
}



↑返回目录
前一篇: J2SE5.0新特性之静态导入
后一篇: J2SE 5.0 Generic应用二:类型安全的out、ref参数