Guava Function&Functions 源码分析

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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章