Java泛型:将泛型函数对象链接在一起

Java泛型:将泛型函数对象链接在一起,第1张

Java泛型:将泛型函数对象链接在一起

这是一种方法。run方法不是类型安全的,但是鉴于附加管道的唯一方法是以类型安全的方式进行,因此整个链都是类型安全的。

public class Chain<S, T> {    private List<Pipe<?, ?>> pipes;    private Chain() {    }    public static <K, L> Chain<K, L> start(Pipe<K, L> pipe) {        Chain<K, L> chain = new Chain<K, L>();        chain.pipes = Collections.<Pipe<?, ?>>singletonList(pipe);;        return chain;    }    public <V> Chain<S, V> append(Pipe<T, V> pipe) {        Chain<S, V> chain = new Chain<S, V>();        chain.pipes = new ArrayList<Pipe<?, ?>>(pipes);        chain.pipes.add(pipe);        return chain;    }    @SuppressWarnings({ "rawtypes", "unchecked" })    public T run(S s) {        Object source = s;        Object target = null;        for (Pipe p : pipes) { target = p.transform(source); source = target;        }        return (T) target;    }    public static void main(String[] args) {        Pipe<String, Integer> pipe1 = new Pipe<String, Integer>() { @Override public Integer transform(String s) {     return Integer.valueOf(s); }        };        Pipe<Integer, Long> pipe2 = new Pipe<Integer, Long>() { @Override public Long transform(Integer s) {     return s.longValue(); }        };        Pipe<Long, BigInteger> pipe3 = new Pipe<Long, BigInteger>() { @Override public BigInteger transform(Long s) {     return new BigInteger(s.toString()); }        };        Chain<String, BigInteger> chain = Chain.start(pipe1).append(pipe2).append(pipe3);        BigInteger result = chain.run("12");        System.out.println(result);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4957726.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-13
下一篇2022-11-13

发表评论

登录后才能评论

评论列表(0条)

    保存