前言
開篇明義: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; }