与类型层次匹配 [英] Matching against type hierarchy

查看:97
本文介绍了与类型层次匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个固定的类型层次结构,例如如下图所示。这是一棵定义明确的树,其中每个节点都有一个父节点(根节点除外)。

Suppose we have a fixed type hierarchy, e.g. as depicted below. It is a well-defined tree, where each node has one parent (except for the root).

每种类型都有一个与之关联的动作,应在成功匹配后执行。这不是不是,它表示操作对应于该类型的方法。只是任意关联。

Each type has an action associated with it, that should be performed upon successful matching. This does not mean that an action corresponds to a method on said type. It's just arbitrary association.

将对象与类型层次结构进行匹配的明智方法是什么?
每个对象应与最具体的类型匹配。已创建对象。

What are intelligent ways to match objects against a type hierarchy? Each object should be matched against the most specific type possible. The objects are already created.

推荐答案

从根开始使用递归搜索。

Use recursive search from the root.

一旦在子级中找不到匹配项,请记住匹配对象的级别是否比上次匹配要深。

Once no match can be found in children, remember the matched object if its level is deeper than the last match.

伪代码:

    class MatchContext {
         public int level;
         public Node result;
    }

    public boolean match(Node object, int level, MatchContext ctx) {
        if (no match)
            return false;
        boolean found = false;
        for (all children in object) {
            if (match(child, level + 1, ctx))
                found = true;
        }
        if (!found && level > ctx.level) {
            ctx.level = level;
            ctx.result = this;
        }
        return found;
    }

像这样调用:

    MatchContext ctx;
    if (match(root, 0, ctx))
        myAction(ctx.result);

这篇关于与类型层次匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆