动态实例化链接对象链

Dynamically instantiating linked object chain

我正在为子字符串搜索实现一个命令链模式。我可以通过编写如下内容来静态创建链:

matchChain = new CharMatcher( new DotMatcher( new CharMatcher(null)));

我在这里明确声明字符串中的每个字符将与模式字符句点字符相匹配("c.c")

但我的目标是为任何给定的键模式动态创建此链。例如 ("\`\`cccc.cc\`\`*c") 将是:

matchChain = new CharMatcher( new CharMatcher( new CharMatcher( new CharMatcher( new CharMatcher(new DotMatcher( new CharMatcher( new CharMatcher( new StarMatcher( new CharMatcher(null)))))));

所以链 class 是一个抽象 class 并且每个匹配器 class 扩展链。

那么我如何根据给定的 key/pattern 的长度动态实例化一个链?

考虑构建器方法(1):

public class ChainBuilder {

    private static final char DOT ='.', STAR = '*';

    public static void main(String[] args) {

        String pattern = "cccc.cc*c";
        Chain chain = chainBuilder(pattern);

        //printout chain structure
        String space ="", step =" ";
        while (true){
            if(chain == null){
                System.out.println(space + chain);
                break;
            }
            System.out.println(space + chain.getClass().getSimpleName());
            space += step;
            chain = chain.getNextLink();
        }
    }

    private static Chain chainBuilder(String pattern){

        Chain chain = null;
        String reversePattern = new StringBuilder(pattern).reverse().toString();
        for(char c : reversePattern.toCharArray()){

            switch (c) {
            case DOT:
                chain = new DotMatcher(chain);
                break;
            case STAR:
                chain = new StarMatcher(chain);
                break;
            default:
                chain = new CharMatcher(chain);
                break;
            }
        }
        return chain;
    }
}


class Chain {

    private final Chain nextLink;

    public Chain(Chain nextLink) {
        this.nextLink = nextLink;
    }

    public Chain getNextLink() {
        return nextLink;
    }
}

class CharMatcher extends Chain{

    public CharMatcher(Chain nextLink) {
        super(nextLink);
    }
}

class DotMatcher extends Chain{

    public DotMatcher(Chain nextLink) {
        super(nextLink);
    }
}

class StarMatcher extends Chain{

    public StarMatcher(Chain nextLink) {
        super(nextLink);
    }
}

(1) 发布的代码是 mre。将整个代码复制粘贴到 ChainBuilder.java 和 运行.