<Java> 全局变量

前言

开篇明义:Java是oop编程,是没有全局变量的概念的。

 

为什么用全局变量

希望能在别的类中引用到非本类中定义的成员变量,有两种方法,一种是参数传递(这是最符合oop编程思想的,但这样会增加参数的个数,而且如这个参数要在线性调用好几次后才使用到,那么会极大增加编程负担),还有一中是定义在一个变量中或类中(这中增加了类之间的耦合,需要引入全局类或)。下面我们这种讨论这种。

 

接口实现

public interface GlobalConstants
{
  String name = "Chilly Billy";
  String address = "10 Chicken head Lane";
}
public class GlobalImpl implements GlobalConstants
{
  public GlobalImpl()
  {
     System.out.println(name);
  }
}

 

在《Effictive Java》中的第4-19篇:Use interfaces only to define types "The constant interface pattern is a poor use of interfaces."还有一句是Constant interface antipattern。
JDK1.5+: you can use static import for your global variables, implementing is not needed。各方都说明这个方法是不可取的。
此外:还有一点就是,我经常在纠结全局变量是定义在class中还是定义在interface中,在看了java官方对全局变量的定义后,我明白了,还是定义在类中比较合适,因为虽然定义在interface中可以完成一样的功能并且还是少写不少final static之类的修饰词,但是这并不符合interface的定义初衷。interface更多的是用来规范或制定行为的。
 

首先一点不推荐使用依赖注入,比如下面:

public class Globals {
    public int a;
    public int b;
}

public class UsesGlobals {
    private final Globals globals;
    public UsesGlobals(Globals globals) {
        this.globals = globals;
    }
}

最后,我们使用最官方的做法(注意使用的import static):

package test;
class GlobalConstant{
    public static final String CODE  = "cd";
}

import static test.GlobalConstant;
public class Test{
  private String str =  GlobalConstant.CODE;
}

 

posted @ 2015-03-31 11:45  丶千纸鸢  阅读(2453)  评论(0编辑  收藏  举报