简体   繁体   English

在Java中导出函数对象的最佳实践是什么?

[英]What is the best practice to export function objects in Java?

在Java中创建function objects (导出一个适用于其他对象的单个方法的无状态对象)的最佳实践是什么?

It's instructive to look at the forthcoming Java 8 functional interfaces 查看即将推出的Java 8功能接口有益的

The Java 8 class library has a new package, java.util.functions, which contains several new functional interfaces. Java 8类库有一个新的包java.util.functions,它包含几个新的功能接口。 Many of these can be used with the Collections API. 其中许多可以与Collections API一起使用。

If you follow the patterns exhibited here, you'll have a functional interface (an interface supporting one method) and an implementation with no members. 如果您遵循此处展示的模式,您将拥有一个功能界面(支持一种方法的界面)和一个没有成员的实现。 Your function object shouldn't call any methods on the method arguments that could change their state (ie exhibit side-effects). 您的函数对象不应该调用可能会改变其状态的方法参数上的任何方法(即表现出副作用)。 Unfortunately you can't enforce that - you have to rely on convention for this. 不幸的是你不能强制执行 - 你必须依赖惯例。

Java是面向对象的编程语言,因此使用策略设计模式。

Java8 should have lambdas to ease the creation of functional interface implementations. Java8应该有lambdas来简化功能接口实现的创建。 Before Java8 you may look at what the guava library offers: Functional Explained 在Java8之前,您可以查看番石榴库提供的内容: 功能说明

Here is an excerpt of the documentation: 以下是文档的摘录:

Guava provides two basic "functional" interfaces: Function, which has the single method B apply(A input). Guava提供了两个基本的“功能”接口:Function,它有单个方法B apply(A input)。 Instances of Function are generally expected to be referentially transparent -- no side effects -- and to be consistent with equals, that is, a.equals(b) implies that function.apply(a).equals(function.apply(b)). 通常期望函数实例是引用透明的 - 没有副作用 - 并且与equals一致,即a.equals(b)意味着function.apply(a).equals(function.apply(b) )。 Predicate, which has the single method boolean apply(T input). 谓词,它有单个方法boolean apply(T输入)。 Instances of Predicate are generally expected to be side-effect-free and consistent with equals. 谓词的实例通常预期是无副作用的并且与equals一致。

Ok after commenting, here is an answer: There is no easy/convenient way to pass a function. 评论后确定,这是一个答案:传递函数没有简单/方便的方法。

Most of the time you will declare an inner class which implements a interface like for example, the Comparator : http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html 大多数情况下,您将声明一个实现接口的内部类,例如Comparatorhttp//docs.oracle.com/javase/6/docs/api/java/util/Comparator.html

The fact that functions cannot be passed as parameters gave rise to a lot of so called design patterns, where you pass around objects classes/interfaces which declare having those functions. 函数不能作为参数传递的事实产生了许多所谓的设计模式,在这些模式中传递声明具有这些函数的对象类/接口。

As mentioned by others life will get a little easier with Java 8. 正如其他人所提到的,使用Java 8可以让生活变得更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM