1

我在我的 Android 应用程序中扩展了我的应用程序,以便存储我在应用程序中使用的不同字体。一切正常,但是我不理解代码的单例部分以及 getInstance 的目标是什么(我在那里设置了一个断点并且它从未被调用,如果我更改方法的名称,应用程序也可以正常工作出色地)。有人可以告诉我这种模式吗?我通常不使用 OOP,所以这可能是一个愚蠢的问题。

我的应用程序.java

    public class MyApplication extends Application {
    private Typeface _typefaceNormal;
    private Typeface _typefaceBold;

    private static MyApplication singleton;

    public MyApplication getInstance() {
        return singleton;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
        this._typefaceNormal = Typeface.createFromAsset(getAssets(),"PTS55F.TTF");
        this._typefaceBold = Typeface.createFromAsset(getAssets(), "PTS75F.TTF");
    }

    public Typeface getNormalFont() {
        return this._typefaceNormal;
        // return this._typefaceNormal;
    }

    public Typeface getBoldFont() {
        return this._typefaceBold;
        // return this._typefaceBold;
    }
}

然后我这样打电话:

this._typeface = ((MyApplication) _activity.getApplicationContext()).getNormalFont();

编辑

根据我收集的答案和一些额外的研究,这是我最终使用的课程:

    public class MyGlobalConfig {
    private static MyGlobalConfig singleton;
    private Typeface _typefaceNormal;
    private Typeface _typefaceBold;

    private MyGlobalConfig() {

    }

    public static MyGlobalConfig getInstance() {
        if (singleton == null) {
            singleton = new MyGlobalConfig();
        }
        return singleton;
    }

    public void init(Context ctx, String typefaceNormal, String typefaceBold) {
        this._typefaceNormal = Typeface.createFromAsset(ctx.getAssets(),
                typefaceNormal);
        this._typefaceBold = Typeface.createFromAsset(ctx.getAssets(),
                typefaceBold);
    }

    public Typeface getNormalFont() {
        return this._typefaceNormal;
        // return this._typefaceNormal;
    }

    public Typeface getBoldFont() {
        return this._typefaceBold;
        // return this._typefaceBold;
    }
}

我将其初始化为:

MyGlobalConfig.getInstance().init(getApplicationContext(), normalFont, boldFont);

并将我的字体设置为:

MyGlobalConfig.getInstance().getNormalFont();
4

2 回答 2

2

单例模式的目的是强制只能创建一个类的一个实例。不过,您在这里并没有真正做到这一点。在 Java 中执行此操作的正确方法是将构造函数设为私有,然后将静态变量设置为类的单例实例。例如:

public class MySingletonClass{
  private static MySingletonClass singleton;

  // private constructor
  private MySingletonClass(){}

  public static MySingletonClass getInstance(){
   if(singleton == null){
     singleton = new MySingletonClass();
   }
   return singleton;
  }
}

在使用 Android 时,无需将 Application 类设置为单例。Android 只会创建它的一个实例并为您管理它。此外,由于 Application 类已经定义了一个公共构造函数,我不相信编译器会允许您在扩展类中将构造函数设为私有,因此您无法强制执行单例模式。

于 2014-11-26T18:43:44.173 回答
1

那是因为您没有使用静态方法 MyApplication.getInstance()。相反,您正在通过 context.getApplicationContext() 访问引用,在这种情况下,这会导致与“单例”静态变量相同的引用。

通过静态方法 getInstance() 访问实例使您能够在没有上下文引用的情况下访问它,并使您免于强制转换 ((MyApplication) _activity.getApplicationContext())。不利的一面是,它会耦合您的代码并使其难以测试。

于 2014-11-26T18:58:16.003 回答