標籤:
前言
開篇明義: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;}
<Java> 全域變數的問題