2015-07-11 70 views
1

在我的應用程序中,我需要處理多個字體文件。因此,而不是每次創建新實例,我實現了辛格爾頓得到字樣這樣的:Android:處理多個字體文件 - 正確的方法

public class FontSingleton { 

    private static FontSingleton instance; 
    private static Typeface typeface; 

    private FontSingleton(){ 
     //private constructor to avoid direct creation of objects 
    } 

    public static FontSingleton getInstance(Context context,String fontFileName){ 
     if(instance==null){ 
      instance = new FontSingleton(); 
      typeface = Typeface.createFromAsset(context.getResources().getAssets(), fontFileName); 
     } 
     return instance; 
    } 

    public Typeface getTypeFace(){ 
     return typeface; 
    } 
} 

現在,我能得到typeface這樣的:

FontSingleton.getInstance(mContext,"font1.otf").getTypeFace(); 

是爲應對正確的方法內存泄漏和實施Singleton?我是設計模式和Android的新手。任何人都可以引導我正確的方式嗎?

回答

3

是沒有用的製作FontSingleton一個Singleton,使你真正需要的是緩存Typeface對象,而不是創建它們的類。因此,您可以使FontSingleton(不再是Singleton,因此我們稱它爲FontHelper)沒有實例的類,並讓它存儲MapTypefaces。這些將以懶惰的方式創建:如果字體名稱沒有Typeface - 創建它並將其存儲在Map中,否則重用現有實例。下面的代碼:

public class FontHelper { 

    private static final Map<String, Typeface> TYPEFACES = new HashMap<>(); 

    public static Typeface get(Context context,String fontFileName){ 
     Typeface typeface = TYPEFACES.get(fontFileName); 
     if(typeface == null){ 
      typeface = Typeface.createFromAsset(context.getResources().getAssets(), fontFileName); 
      TYPEFACES.put(fontFileName, typeface); 
     } 
     return typeface; 
    } 
} 

很抱歉,如果代碼不作爲是工作,但希望這個想法是清楚的。

1

是正確的方式來處理內存泄漏和實施 單身?

getInstance()應該是​​,你標記後作爲​​,那麼,有什麼涉及模式的實現是正確的。不過,我認爲這並不適合你的需要。例如,你不能創建一個新的TypeFace對象。你寫的方式你使用font1.otf卡住了。如果你想要的話,比你不需要提供字體名稱,作爲getInstance()的參數。

作爲替代解決方案,您應考慮子類TextView的可能性,提供一個自定義xml屬性,通過它可以指定要使用的字體。

+0

謝謝,但「你不需要提供fontname,作爲getInstance()的參數」。那我該怎麼做呢? –

+0

硬編碼它直接在'createFromAsset' – Blackbelt

+0

,但正如我所說我需要處理多種字體。我應該有多種方法來獲取實例嗎? –

1

如果我看得很清楚,這是過度複雜和不正確的(由於實例已經存在,實例將始終保留已給出的第一個字體,因爲它不會被再次調用)。

爲什麼不執行這樣的事情:

public class FontHelper { 
    public static Typeface get(Context context, String fontFilename) { 
     return Typeface.createFromAsset(context.getResources().getAssets(), fontFileName); 
    } 
} 

然後您只要致電:

FontHelper.get(mContext,"font1.otf")

+3

我也會在靜態HashMap中緩存字體。 – Karakuri

+1

通過這種方法,每次調用get()方法時都會創建一個新的字體,並且檢索資源是一項非常昂貴的操作:此代碼將非常慢。 – Egor

+0

@Karakuri我同意。這只是從我的頭頂開始。 –

相關問題