枚举与静态常量比较
?
静态常量是枚举模式的应用
它有很多缺点:类型不安全(静态常量可以随意增加使用或操作),无命名空间,脆弱(某常量值改变后客户端如果不编译仍能使用,但表现却是未定义的),静态常量打印值为数字,也不具提示性等等
?
?
客户端未编译有待推敲?
?
?
This pattern has many problems, such as:
Not typesafe - Since a season is just anint
you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).No namespace - You must prefix constants of an int enum with a string (in this case SEASON_
) to avoid collisions with other int enum types.Brittleness - Because int enums are compile-timeconstants, they are compiled into clients that use them. If a newconstant is added between two existing constants or the order ischanged, clients must be recompiled. If they are not, they will stillrun, but their behavior will be undefined.Printed values are uninformative - Because they arejust ints, if you print one out all you get is a number, which tellsyou nothing about what it represents, or even what type it is.脆弱性的理解在这里比如是静态常量,修改了,插入或者增加,客户端必须得重新编译来适应新的变化,而枚举的话则不必,比如它可以通过遍历来囊括所有新的变化,客户端代码可以不用改变,这就是用静态常量脆弱性的体现。
?