ACYCLIC VISITOR模式解决Shape排序问题

来源:互联网 发布:开源旅游cms 编辑:程序博客网 时间:2024/06/05 15:56
Robert C Martin 在他OCP(Open/Closed Principle,可以参考<<Agile Principles Patterns and Practices in C#>>)的教程里,以Shape作为例子,介绍如何运用OCP。

但是有一个问题没有给答案,只是说:
“It is possible to solve this problem by using the ACYCLIC VISITOR pattern described in Chapter 35. Showing that solution now
would be getting ahead of ourselves a bit. I'll remind you to come back here at the end of that chapter.”

我刚好看过ACYCLIC VISITOR模式,对这个模式如何解决Shape排序输出摸不到头脑,还专门在CSDN的C#论坛发帖。

自己动手,丰衣足食,我能想到的解决方案如下:

将Shape和OrderedObject分开,可以避免违反SRP。
方案的关键是可以在MyShapeVisitor里面设置每个Shape子类的优先级,如果要修改,只改这一个类即可。
如果Shape有新的子类,如Triangle,只要添加一个新的接口TriangleVisitor,在MyShapeVisitor里面
实现这个新接口,同时按需调整各Shape子类的优先级就可以了。

0 0
原创粉丝点击