<Java> 全域變數的問題

來源:互聯網
上載者:User

標籤:

前言

開篇明義: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> 全域變數的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.