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排序输出摸不到头脑,还专门在优快云的C#论坛发帖。
自己动手,丰衣足食,我能想到的解决方案如下:
将Shape和OrderedObject分开,可以避免违反SRP。
方案的关键是可以在MyShapeVisitor里面设置每个Shape子类的优先级,如果要修改,只改这一个类即可。
如果Shape有新的子类,如Triangle,只要添加一个新的接口TriangleVisitor,在MyShapeVisitor里面
实现这个新接口,同时按需调整各Shape子类的优先级就可以了。
本文探讨了Robert C. Martin在其OCP原则教程中提到的使用ACYCLIC VISITOR模式解决Shape类排序输出的问题。通过将Shape与OrderedObject分离并利用MyShapeVisitor设置优先级的方式,有效地遵循了单一职责原则。
88

被折叠的 条评论
为什么被折叠?



