J2SE 5.0 Generic应用一:类型安全的functor

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

一、简介

函数式编程是非常常用和非常重要的一种编程范式,有的语言直接提供支持,C++则通过()运算符重载和模板提供了还算灵活的支持,而Java中的函数式编程则由于语言本身的局限没有得到广泛应用,Apache Commons Functor 项目是一个正在开发中的函数式编程库,但目前看来并不是类型安全的;J2SE 5.0提供了有限的generic能力,除了用于Collection之外,类型安全的functor也是其用武之地,已有一个开源项目Generic Algorithms for Java开始了这方面的工作

二、示例

一元函数、谓词、过程

public interface UnaryFunction<R, P> {

R evaluate(P obj);

}

public interface UnaryPredicate<T> {

boolean test(T obj);

}

public interface UnaryProcedure<T> {

void run(T obj);

}

二元函数、谓词、过程

public interface BinaryFunction<R, T, S> {

R evaluate(T left, S right);

}

public interface BinaryPredicate<T, S> {

boolean test(T left, S right);

}

public interface BinaryProcedure<T, S> {

void run(T left, S right);

}

特化一:过滤

public interface Filter<T> extends UnaryFunction<T, T>{

}

几个示例算法:transform、select、foreach

public static <Destination, Source> List<Destination> transform(Collection<Source> source, UnaryFunction<Destination, Source> transformer){

List<Destination> result = new ArrayList<Destination>();

for(Source item : source){

result.add(transformer.evaluate(item));

}

return result;

}

public static <T> List<T> select(Collection<T> source, UnaryPredicate<T> selector){

List<T> result = new ArrayList<T>();

for(T item : source){

if(selector.test(item)){

result.add(item);

}

}

return result;

}

public static <T> void foreach(Collection<T> source, UnaryProcedure<T> procedure){

for(T item : source){

procedure.run(item);

}

}

几个composite:And、Or、Not

public class And<T> implements UnaryPredicate<T>, Serializable{

private UnaryPredicate<T>[] predicates;

public And(UnaryPredicate<T>... predicates){

this.predicates = predicates;

}

public boolean test(T obj) {

for(UnaryPredicate<T> predicate : predicates){

if( !predicate.test(obj) ){

return false;

}

}

return true;

}

public static <T> And<T> and(UnaryPredicate<T>... predicates){

return new And<T>(predicates);

}

}

public class Or<T> implements UnaryPredicate<T>, Serializable{

private UnaryPredicate<T>[] predicates;

public Or(UnaryPredicate<T>... predicates){

this.predicates = predicates;

}

public boolean test(T obj) {

for(UnaryPredicate<T> predicate : predicates){

if( predicate.test(obj) ){

return true;

}

}

return false;

}

public static <T> Or<T> or(UnaryPredicate<T>... predicates){

return new Or<T>(predicates);

}

}

public class Not<T> implements UnaryPredicate<T>, Serializable{

private UnaryPredicate<T> predicate;

public Not(UnaryPredicate<T> predicate){

this.predicate = predicate;

}

public boolean test(T obj) {

return !predicate.test(obj);

}

public static <T> Not<T> not(UnaryPredicate<T> predicate){

return new Not<T>(predicate);

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航