诊断Java代码: 深度优先访问器和中断的分派2011-02-11 IBM Eric E. Allen设计模式最多只能对快速集中到一个项目的简单设计提供很大帮助。但是,在一个特定环境中实现一种设计模式的最简单方法并不一定是显而易见的 ― 要做到这一点,有许多种方法。这个月,我们将讨论应用公共设计模式来产生简单、简短且健壮的代码的一些方法。首先,让我们看一下两种模式,它们适用于许多不同的环境。在 设计模式(Erich Gamma 等,也称为“四从组(Gang of Four)”著,它介绍了该主题的一些基础知识(请参阅 参考资料))中讨论的所有设计模式中,我发现可最广泛应用的是 Composite 和 Visitor 模式。让我们进一步研究这两种模式。用 Composite 指定递归数据类型很容易就可以看出为什么 Composite 模式是有用的。Composite 模式只是指定递归定义的数据类型的面向对象方法;这些机会始终出现在软件开发中。研究递归定义的对象类型的能力是软件工程的最显著的特征之一(与数字设计成对比,系统是从有限状态的机器构建的)。用 Visitor 扩展类层次结构至于 Visitor 模式,它受到如此广泛应用的许多原因是它补充了 Composite 模式。Visitor 常常被吹捧为无需实际修改现有复合类层次结构中的类就可扩展其功能的一种方法。但是,它们的能力远远不仅于此。因为访问器允许您将一个类层次结构的某些功能与类本身分开,所以可以在各式各样的设置中使用它们,在这些设置中,从概念上很难将功能看作是那些类的固有部分。这种现象常常出现在复合数据结构上的向下递归中。例如,考虑二叉树的类层次结构和确定树中的任何节点是否包含一个零的访问器:清单 1. 带访问器的二叉树abstract class Tree { public abstract Boolean accept(TreeVisitor that); } class Leaf extends Tree { public static final Leaf ONLY = new Leaf(); public Boolean accept(TreeVisitor that) { return that.forLeaf(this); } } class Branch extends Tree { public int value; public Tree left; public Tree right; public Branch(int _value, Tree _left, Tree _right) { this.value = _value; this.left = _left; this.right = _right; } public Boolean accept(TreeVisitor that) { return that.forBranch(this); } } interface TreeVisitor { public Boolean forLeaf(Leaf that); public Boolean forBranch(Branch that); } class ZeroFinder implements TreeVisitor { public Boolean forLeaf(Leaf that) { return new Boolean(false); } public Boolean forBranch(Branch that) { if (that.value == 0) { return new Boolean(true); } boolean foundInLeft = that.left.accept(this).booleanValue(); boolean foundInRight = that.right.accept(this).booleanValue(); return new Boolean(foundInLeft || foundInRight); } }