【问题标题】:Is there a difference between the way these two usages of a constructor work?构造函数的这两种用法的工作方式有区别吗?
【发布时间】:2014-11-22 19:58:33
【问题描述】:

我的 Android 应用程序中有一个应用程序类,我们称之为

MyApplication.

我有实用程序类,我在其中实例化一次,然后在应用程序中的任何地方使用

让我们说:

TimeConverter
ImageManager

现在,我需要将它们传递到某个 asynctask 类的构造函数中

这两种方式有区别吗?:

变体 1:

我分别通过了每一个

MyApplication application = (MyApplication) getApplication();

new SomeAsyncTask(application.timeConverter, application.imageManager).execute():


class SomeAsyncTask extends AsyncTask<Void, Void, Void> {

    TimeConverter timeConverter;
    ImageManager imageManager;


    public SomeAsyncTask(TimeConverter timeConverter, ImageManager imageManager) {
        this.timeConverter = timeConverter;
        this.imageManager = imageManager;
    }

    doInBackground...

}

变体 2:

MyApplication application = (MyApplication) getApplication();

new SomeAsyncTask(application).execute():


class SomeAsyncTask extends AsyncTask<Void, Void, Void> {

    TimeConverter timeConverter;
    ImageManager imageManager;


    public SomeAsyncTask(MyApplication application) {
        this.timeConverter = application.timeConverter;
        this.imageManager = application.imageManager;
    }

    doInBackground...

}

那么从 OOP 的角度(或任何其他角度)来看,这两种使用构造函数的方式是否存在一些明显的区别

【问题讨论】:

    标签: java android


    【解决方案1】:

    实际上并没有什么不同,但变体 2 更灵活。

    因为如果你想扩展构造,调用者不需要改变方法,所有的新参数(例如Stringconverter或类似的东西)也可以在应用程序对象中。

    这个原理在 Java 中称为值对象或 DTO(数据传输对象) 见:http://martinfowler.com/bliki/ValueObject.html

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2010-11-03
      相关资源
      最近更新 更多