【问题标题】:What is the dot-notation between class names and what does it mean?类名之间的点表示法是什么意思?
【发布时间】:2013-10-02 14:14:33
【问题描述】:

这个.notation (AlertDialog.Builder) 在类构造函数中是什么意思?

public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
        .setTitle(R.string.date_picker_title)
        .setPositiveButton(android.R.string.ok, null)
        .create();

}

是不是说Builder类是在AlertDialog类里面定义的?或者 Builder 是一种方法,但是它的第一个字母是大写的,所以我很困惑。

【问题讨论】:

  • 留意建造者模式。
  • 那是fluent。为了清楚起见,他们只是插入了换行符。
  • 请参阅here 以获取有关方法链接的更多信息,并记住空格对编译器来说基本上没有意义。想象一下这一切都在一条线上

标签: java android syntax


【解决方案1】:

BuilderAlertDialog 类的静态内部类。

我建议你阅读this 了解嵌套类的使用和实用性

【讨论】:

    【解决方案2】:

    这种模式称为method chaining

    Builder 是 AlertDialog 的一个静态内部类。

    Builder 中的每个方法都返回一个 Builder(通常是“this”)而不是 void。

    【讨论】:

      【解决方案3】:

      Check out the documentation!

      Builder 是在AlertDialog 类中定义的静态类。你称它为构造函数。

      【讨论】:

        【解决方案4】:

        这意味着Builder是AlertDialog类中的一个静态嵌套类,即

        class AlertDialog {
        
           static class Builder {
        ..
        

        【讨论】:

          【解决方案5】:

          这是Builder design pattern

          你在代码中做了什么:

          • 创建 Builder 类的实例 - new AlertDialog.Builder(getActivity())
          • 设置其属性调用setTitlesetPositiveButton
          • 通过使用 Builder 的属性调用 create() 方法来创建 AlertDialog 的实例。

          建造者模式是一种创造型设计模式,这意味着它解决了与对象创建相关的问题。 Java中的构造函数用于创建对象,并且可以获取创建对象所需的参数。当可以使用大量参数创建对象时,问题就开始了,其中一些可能是强制性的,而另一些可能是可选的。当构造函数中所需的参数数量超过可管理的数量(通常为 4 或最多 5 个)时,应使用 Builder 设计模式。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-21
            • 2020-01-01
            • 1970-01-01
            • 2013-11-12
            • 2022-12-01
            • 2016-08-17
            • 2017-03-02
            • 1970-01-01
            相关资源
            最近更新 更多