多态与职责划分:如何避免“开启类型" [英] Polymorphism vs. division of responsibilities: how to avoid 'switching on type'

查看:89
本文介绍了多态与职责划分:如何避免“开启类型"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计具有层次关系的系统时,我经常遇到一个乞求多态行为的问题,但是有多种类型的工作可以从这种多态实现中受益.

In designing systems with hierarchical relationships, I often run into a problem that begs for polymorphic behavior, but there is more than one type of work that benefits from this polymorphic implementation.

例如,考虑使用抽象语法树来组织已解析的源以进行编译的编译器.多态组织逻辑很方便,因为您可能拥有不止一种类型的ValueProvider,每种类型的ValueProvider负责发出不同的代码以将值加载到操作堆栈上.问题在于,您可能还想对AST执行静态分析,在这种情况下,您希望对树进行完全不同的工作,但是其行为可能取决于所分析的节点的类型.换句话说,您想要多态行为,但是您不想将分析代码与编译代码混合在一起.

For instance, consider a compiler that uses an abstract syntax tree to organize the parsed source for compilation. It's convenient to organize the logic polymorphically, as you might have more than one type of ValueProvider, each of which is responsible for the emission of different code to load the value onto the operation stack. The problem is that you might also want to perform static analysis on the AST, in which case you want to do completely different work with the tree, but nevertheless may have behavior that depends on the type of the node being analyzed. In other words, you want polymorphic behavior, but you don't want to co-mingle the analysis code with the compilation code.

我目前的处理方式是使用对象模型存储数据,该对象模型仅负责提供树.然后,树的每个使用者(例如,编译器或静态分析器)都使用运行时类型信息来对其逻辑进行条件分支.基于节点的类型,这不可避免地导致大量的"if/else if"或"switch"编码.多态性旨在解决这种类型的丑陋分支,但是并行,不相交的职责似乎是必需的.

The way I currently approach this is to store the data with an object model whose responsibility is to merely provide the tree. Each consumer of the tree (e.g. the compiler or the static analyzer) then uses run-time type information to perform conditional branching of its logic. This inevitably leads to a lot of 'if/else if' or 'switch' coding, based on the type of the nodes. It's just this type of ugly branching that polymorphism is designed to address, but the parallel, disjoint responsibilities seem to require it.

是否有更好的方法来构造它?

Is there a better way to structure this?

推荐答案

您似乎正在寻找访问者模式:

访问者设计模式是将算法与操作对象的对象结构分开的一种方式.这种分离的实际结果是能够在不修改对象结构的情况下向其现有对象结构添加新操作.

the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.

(重点是我的)

这篇关于多态与职责划分:如何避免“开启类型"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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