2011-12-13 88 views
4

我需要創建某個類的一個實例 - 並且這個實例需要可以從代碼中的任何地方訪問。如何使用Guice的@Singleton?

所以,我找到了Guice ......並且我想從這個包中使用'@Singleton',但是我沒有找到任何示例或一些文檔來告訴我如何使用它以及如何進行聲明。

+0

您應該檢查roboguice.org – Macarse

+0

我檢查......這仍然是無法理解 – Yanshof

+0

這是Android的關係嗎? –

回答

4

好吧,我的回答是不特定的吉斯的@Singleton,但如果你想一類是通過訪問你所有的活動,然後我認爲,您必須使用應用類的Android。 (這是我個人的看法您的需求)

做到這一點的方法是創建自己的android.app.Application子類,然後指定類應用程序中的標籤在你的清單。現在,Android會自動創建該類的一個實例,並使其可用於整個應用程序。可以從任何上下文使用Context.getApplicationContext()方法(活動還提供了一種方法getApplication()其具有完全相同的效果)訪問它:

class MyApp extends Application { 

    private String myState; 

    public String getState(){ 
    return myState; 
    } 
    public void setState(String s){ 
    myState = s; 
    } 
} 

class Blah extends Activity { 

    @Override 
    public void onCreate(Bundle b){ 
    ... 
    MyApp appState = ((MyApp)getApplicationContext()); 
    String state = appState.getState(); 
    ... 
    } 
} 

這具有基本上如使用靜態變量或單相同的效果,但相當集成進入現有的Android框架。請注意,這不適用於各個流程(如果您的應用程序是具有多個進程的罕見應用程序之一)。

下面是有關如何使用它漂亮的教程,Extending the Android Application class and dealing with Singleton

+0

謝謝!我真的是新的'安卓'..所以這是非常有幫助的! – Yanshof

+0

更簡單的是使用Scala語言代替。你可以定義一個'object'並完成:它可以從任何Activity和其他類訪問。這實際上就像實施單件工廠,但斯卡拉自動爲你做這一切。 –

7

@Singleton非常易於使用。它只是這樣

@Singleton 
public class A { 

    @Inject 
    public A() { 
    } 
} 

但是請注意,單是每一個VM的每個噴射不能及的。 Singleton是一個範圍類型,GUICE還允許自定義範圍,這可能非常有用。請參閱下面的鏈接。

當你在另一個類中使用它時,你只需要注入它。

public class B { 
    @Inject 
    public B(A a) { 
    } 
} 

http://code.google.com/p/google-guice/wiki/Scopes

http://code.google.com/p/google-guice/wiki/GettingStarted

+0

那麼,在公共B(A a)中......它總是需要在puclic C(A a)中創建的同一個實例嗎? – Yanshof

+2

只要您的注射器是相同的。它基本上是一個範圍實例。所以在那個對象中,層次結構實例「a」在該注入器下將是相同的。 –

+1

請注意,Guice有很多方法可以做同樣的事情。我們也可以在configure()中使用bind(Iface.class).to(Impl.class).in(Scopes.SINGLETON)進行綁定時在模塊中指定singleton-ness,但是我發現Guice 3.0並不總能保證唯一性使用Module.configure()中的綁定註釋。 @SidMalni的解決方案似乎解決了Module.configure()綁定方法的問題。 – jlb

1
public class DestinationViewManger { 

    private static final DestinationViewManger instance = new DestinationViewManger(); 
    public Boolean flag=false; 

// Private constructor prevents instantiation from other classes 
    private DestinationViewManger(){ } 

    public static DestinationViewManger getInstance() { 
     return instance; 
    } 
} 

//嘗試這一次單例類。不需要getter和setter方法

DestinationViewManger dstv; 

dstv=DestinationViewManger.getInstance(); 

dstv.flag=true; //set the value for your flag 

boolean whatFlagboo=dstv.flag; //get your flag wherever you want