Functional Programming
函數式編程強調使用函數來實現其目標或者改變其狀態。
Guava爲了支持函數式編程提供了三個類Predicate、Function、Supplier。
Function
輸入一個input,輸出一個output。爲了兼容Java8,也繼承了Java的Function接口。
Function接口中有兩個方法,主要對apply方法進行研究。
package com.google.common.base;
@GwtCompatible
@FunctionalInterface
public interface Function<F, T> extends java.util.function.Function<F, T> {
@Override
@Nullable
@CanIgnoreReturnValue // TODO(kevinb): remove this
T apply(@Nullable F input);
@Override
boolean equals(@Nullable Object object);
}
Functions類,包含了一些實用的靜態方法來操作Function接口的實例。主要研究apply方法,一個好的Function實現應該沒有副作用,也就是說對象作爲參數傳遞方法調用apply方法後應保持不變。
package com.google.common.base;
@GwtCompatible
public final class Functions {
private Functions() {}
/**
* 類似於toString方法
* Functions.toStringFunction.apply(o);
*/
public static Function<Object, String> toStringFunction() {
// 返回ToStringFunction的唯一枚舉單例實例
return ToStringFunction.INSTANCE;
}
// enum singleton pattern枚舉單例
private enum ToStringFunction implements Function<Object, String> {
INSTANCE;
@Override
public String apply(Object o) {
checkNotNull(o); // eager for GWT.
return o.toString();
}
@Override
public String toString() {
return "Functions.toStringFunction()";
}
}
// 標識
@SuppressWarnings("unchecked")
public static <E> Function<E, E> identity() {
// 返回ToStringFunction的唯一枚舉單例實例
return (Function<E, E>) IdentityFunction.INSTANCE;
}
// enum singleton pattern
private enum IdentityFunction implements Function<Object, Object> {
INSTANCE;
@Override
@Nullable
public Object apply(@Nullable Object o) {
return o;
}
@Override
public String toString() {
return "Functions.identity()";
}
}
/**
* map相關操作,傳入key返回對應value
* Object value = Functions.forMap(map).apply(key));
*/
public static <K, V> Function<K, V> forMap(Map<K, V> map) {
return new FunctionForMapNoDefault<K, V>(map);
}
private static class FunctionForMapNoDefault<K, V> implements Function<K, V>, Serializable {
final Map<K, V> map;
FunctionForMapNoDefault(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
public V apply(@Nullable K key) {
V result = map.get(key);
// 結果爲null或者不存在這個key報錯
checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key);
return result;
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof FunctionForMapNoDefault) {
FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
return map.equals(that.map);
}
return false;
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public String toString() {
return "Functions.forMap(" + map + ")";
}
private static final long serialVersionUID = 0;
}
/**
* map相關操作,如果key對應的value不存在,將會返回默認值
* Functions.forMap(map, defaultValue).apply(nonExistentKey);
*/
public static <K, V> Function<K, V> forMap(Map<K, ? extends V> map, @Nullable V defaultValue) {
// 傳入默認值
return new ForMapWithDefault<K, V>(map, defaultValue);
}
private static class ForMapWithDefault<K, V> implements Function<K, V>, Serializable {
final Map<K, ? extends V> map;
final V defaultValue;
ForMapWithDefault(Map<K, ? extends V> map, @Nullable V defaultValue) {
this.map = checkNotNull(map);
this.defaultValue = defaultValue;
}
@Override
public V apply(@Nullable K key) {
V result = map.get(key);
return (result != null || map.containsKey(key)) ? result : defaultValue;
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof ForMapWithDefault) {
ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(map, defaultValue);
}
@Override
public String toString() {
// TODO(cpovirk): maybe remove "defaultValue=" to make this look like the method call does
return "Functions.forMap(" + map + ", defaultValue=" + defaultValue + ")";
}
private static final long serialVersionUID = 0;
}
/**
* 混合器,apply將a轉爲b,再將b轉爲c
*
*/
public static <A, B, C> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) {
return new FunctionComposition<A, B, C>(g, f);
}
private static class FunctionComposition<A, B, C> implements Function<A, C>, Serializable {
private final Function<B, C> g;
private final Function<A, ? extends B> f;
public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) {
this.g = checkNotNull(g);
this.f = checkNotNull(f);
}
@Override
public C apply(@Nullable A a) {
// 將a使用Function f轉爲B類型,再用Function g將其轉爲C類型
return g.apply(f.apply(a));
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof FunctionComposition) {
FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
return f.equals(that.f) && g.equals(that.g);
}
return false;
}
@Override
public int hashCode() {
return f.hashCode() ^ g.hashCode();
}
@Override
public String toString() {
// TODO(cpovirk): maybe make this look like the method call does ("Functions.compose(...)")
return g + "(" + f + ")";
}
private static final long serialVersionUID = 0;
}
/**
* 斷言,判斷變量是否滿足條件,返回一個Boolean變量
*
*/
public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
// 傳入一個Guava的Predicate進行斷言
return new PredicateFunction<T>(predicate);
}
/** @see Functions#forPredicate */
private static class PredicateFunction<T> implements Function<T, Boolean>, Serializable {
private final Predicate<T> predicate;
private PredicateFunction(Predicate<T> predicate) {
this.predicate = checkNotNull(predicate);
}
@Override
public Boolean apply(@Nullable T t) {
return predicate.apply(t);
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof PredicateFunction) {
PredicateFunction<?> that = (PredicateFunction<?>) obj;
return predicate.equals(that.predicate);
}
return false;
}
@Override
public int hashCode() {
return predicate.hashCode();
}
@Override
public String toString() {
return "Functions.forPredicate(" + predicate + ")";
}
private static final long serialVersionUID = 0;
}
/**
* 返回一個構造時傳入的常量
*
*/
public static <E> Function<Object, E> constant(@Nullable E value) {
return new ConstantFunction<E>(value);
}
private static class ConstantFunction<E> implements Function<Object, E>, Serializable {
private final E value;
public ConstantFunction(@Nullable E value) {
this.value = value;
}
@Override
public E apply(@Nullable Object from) {
// 返回傳入的value
return value;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof ConstantFunction) {
ConstantFunction<?> that = (ConstantFunction<?>) obj;
return Objects.equal(value, that.value);
}
return false;
}
@Override
public int hashCode() {
return (value == null) ? 0 : value.hashCode();
}
@Override
public String toString() {
return "Functions.constant(" + value + ")";
}
private static final long serialVersionUID = 0;
}
/**
* 返回一個值
*
*/
public static <T> Function<Object, T> forSupplier(Supplier<T> supplier) {
// // 傳入一個Guava的Supplier
return new SupplierFunction<T>(supplier);
}
/** @see Functions#forSupplier */
private static class SupplierFunction<T> implements Function<Object, T>, Serializable {
private final Supplier<T> supplier;
private SupplierFunction(Supplier<T> supplier) {
this.supplier = checkNotNull(supplier);
}
@Override
public T apply(@Nullable Object input) {
return supplier.get();
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof SupplierFunction) {
SupplierFunction<?> that = (SupplierFunction<?>) obj;
return this.supplier.equals(that.supplier);
}
return false;
}
@Override
public int hashCode() {
return supplier.hashCode();
}
@Override
public String toString() {
return "Functions.forSupplier(" + supplier + ")";
}
private static final long serialVersionUID = 0;
}
}