Java Generics: chaining together generic function object

前端 未结 2 1882
轮回少年
轮回少年 2021-02-02 03:23

I\'ve been struggling with the following problem. I have a series of function objects, each with it\'s own input and output types defined via generic type arguments in java. I w

2条回答
  •  我在风中等你
    2021-02-02 03:43

    Here's a way to do it. The run method is not typesafe, but given that the only way to append a pipe is to do it in a type-safe way, the whole chain is type-safe.

    public class Chain {
        private List> pipes;
    
        private Chain() {
        }
    
        public static  Chain start(Pipe pipe) {
            Chain chain = new Chain();
            chain.pipes = Collections.>singletonList(pipe);;
            return chain;
        }
    
        public  Chain append(Pipe pipe) {
            Chain chain = new Chain();
            chain.pipes = new ArrayList>(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 pipe1 = new Pipe() {
                @Override
                public Integer transform(String s) {
                    return Integer.valueOf(s);
                }
            };
            Pipe pipe2 = new Pipe() {
                @Override
                public Long transform(Integer s) {
                    return s.longValue();
                }
            };
            Pipe pipe3 = new Pipe() {
                @Override
                public BigInteger transform(Long s) {
                    return new BigInteger(s.toString());
                }
            };
            Chain chain = Chain.start(pipe1).append(pipe2).append(pipe3);
            BigInteger result = chain.run("12");
            System.out.println(result);
        }
    }
    

提交回复
热议问题