静态常量是枚举模式的应用
它有很多缺点:类型不安全(静态常量可以随意增加使用或操作),无命名空间,脆弱(某常量值改变后客户端如果不编译仍能使用,但表现却是未定义的),静态常量打印值为数字,也不具提示性等等
客户端未编译有待推敲?
This pattern has many problems, such as:
-
Not typesafe
- Since a season is just an
int
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-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
- Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.
脆弱性的理解在这里比如是静态常量,修改了,插入或者增加,客户端必须得重新编译来适应新的变化,而枚举的话则不必,比如它可以通过遍历来囊括所有新的变化,客户端代码可以不用改变,这就是用静态常量脆弱性的体现。