zoukankan      html  css  js  c++  java
  • Interfaces with Constants Only(java中通用常量定义)

    Interfaces with Constants Only

    Before the static import became available, a trick for avoiding the need to write the class name for static constants was to create an interface whose only purpose is to hold constants.

    For example, say that you need the constants ALPHA and OMEGA for several different programs. The first option is to create a utility class that holds the constants. e.g.:

     

    1  public class MyConstants 
    2  {
    3     final static double ALPHA = 1.1;
    4     final static double OMEGA = 901.0
    5  }

     

    Then in your other classes, you would refer to these constants with

     

    1public class OtherClass
    2{
    3   public OtherClass()
    4   {
    5     System.out.println("MyConstants.ALPHA ="+MyConstants.ALPHA );
    6
    7     System.out.println("MyConstants.OMEGA ="+MyConstants.OMEGA );
    8  }

    9}

     

    However, placing the MyConstants class name wherever these constants appear can be tedious and also makes the code less readable, especially in a formula like

       x = (3.1 * MyConstants.ALPHA)/(1.0 + MyConstants.OMEGA);

    An alternative is to put the constants into an interface. This will not interfere with the class design since there is no limit to the number of interfaces that a class can implement.

     

    1  public interface MyConstantsImpl 
    2  {
    3    static final double ALPHA = 1.1;
    4    static final double OMEGA = 901.0
    5  }

     

    Any class that needs these constants can implement MyConstantsImpl. The methods in the program will then refer to the constants simply with ALPHA and OMEGA.

    Then a method in the class that implements MyConstantsImpl could use the constants in an equation without the class reference:

       x = (3.1*ALPHA)/(1.0 + OMEGA);

    1public class OtherClass implements MyConstantsImpl
    2{
    3   public OtherClass()
    4   {
    5     System.out.println("ALPHA ="+ALPHA );
    6
    7     System.out.println("OMEGA ="+OMEGA );
    8  }

    9}


    whcih is far more readable.

    This technique, however, violates the object-oriented design of the language. That is, you are not really implementing anything. You would not think of a class that implements MyConstantsImpl as a MyConstants object in the sense of taking on an identifiable behavior of an interface.

    So constants-only interfaces are ill advised and considered bad programming style . Use a class instead and then statically import the class.

  • 相关阅读:
    LoginStatus 如何指向不同的登陆地址以及“invalid FORMATETC”
    不排序和可以重复Key的SortedList。
    一个新样式
    如何给另一个桌面的程序发送消息?
    Html使用自定义光标的一点需要注意的小问题。
    用stream.Read不能完整读取内容的问题。
    全国天气预报代码(转帖)
    Access处理DISTINCT的Bug?
    asp.net和asp运行结果不同?
    学习枚举类型/FlagsAttribute属性
  • 原文地址:https://www.cnblogs.com/jssy/p/348889.html
Copyright © 2011-2022 走看看