Java中的常量:如何避免反模式

参考 http://www.importnew.com/16700.html

我们可以将类设置为final,这样就不能扩展。甚至,我们可以将构造器设置为私有的,以防止对这个类实例化,这样就永远不会破坏约定。此外,如果一个特殊的常量在同一个类中被多次使用,则开发者可以使用静态引入。

所有对于常量类,比较好的设计应该是:

package three;
//make the class non-extendable by adding final 增加final关键字来避免继承
public final class Constants {
//Hide the constructor 隐藏构造器
private Constants(){}
public static String NAME="name";
}

静态引入的例子:
import static three.Constants.NAME;
public class UseConstants {
  public static void main(String[] args) {
      System.out.println("the value of constants is"+NAME);
  }
}

这个设计问题也称为接口常量反模式(Constant Interface Anti-pattern)。

猜你喜欢

转载自fengjiangtao.iteye.com/blog/2250405