且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用多态性替换条件 - 理论上很好,但不实用

更新时间:2023-09-24 23:13:34

你是对的——条件被推到链的顶端"——但没有公正"的.它非常强大.正如@thkala 所说,您只需选择一次;从那时起,对象就知道如何开展业务了.您描述的方法——BaseAction、ViewAction 和其他方法——是一种很好的方法.试试看,看看你的代码会变得多干净.

You're right - "the conditionals are getting pushed up to the top of the chain" - but there's no "just" about it. It's very powerful. As @thkala says, you just make the choice once; from there on out, the object knows how to go about its business. The approach you describe - BaseAction, ViewAction, and the rest - is a good way to go about it. Try it out and see how much cleaner your code becomes.

当你有一个工厂方法,它接受一个像View"这样的字符串并返回一个动作,你调用它,你已经隔离了你的条件.那太棒了.除非你尝试过,否则你无法正确地欣赏它的力量——所以试一试吧!

When you've got one factory method that takes a string like "View" and returns an Action, and you call that, you have isolated your conditionality. That's great. And you can't properly appreciate the power 'til you've tried it - so give it a shot!