2015-07-11 72 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我同意。这只是从我的头顶开始。 –

相关问题