比如说Color接口有三个实现类分别是:Red、Blue和Green
现在我要在运行的时候才决定用某个实现类
怎么管理比较优雅?别if..else..
ringa_lee2017-04-18 10:54:49
In programming, 顺序
、分支
、循环
三种结构。if-else
is the most commonly used branch structure and is indispensable.
Regarding this issue, if-else
is the simplest programming method for anyone who has learned programming. And the simplest is the most elegant.
And what if-else
有时候看起来比较糟糕的地方在于,if
中嵌套很多层if-else
sometimes looks bad is that there are many layers nested in if
if
的的时候就提前返回结果,保证if
So a good solution is to limit the maximum depth of early exit
Here is a similar question you can look at:
简单的设计
与设计模式
Design patterns can bring you convenience, but don’t force design patterns into your own solutions. You need to make compromises between
PHP中文网2017-04-18 10:54:49
The title description feels more in line with the design pattern 策略模式
.
怪我咯2017-04-18 10:54:49
Why not use polymorphism and leave it to implicit type conversion? It is handled according to the implementation of the interface method.