在没有任何引用的情况下在同一对象上调用多个方法

时间:2018-12-26 11:01:38

标签: java android kotlin

我创建了服装视图, 而且大多数情况下不需要引用它,
实例化后,它足以调用其方法并立即设置其所有值。

所以我的问题是:
如何允许在没有引用的对象上调用多个方法

例如

AlertDialog.Builder(view.context)  
    .setTitle(title)  
    .setMessage(msg)  
    .show()

他们怎么做

3 个答案:

答案 0 :(得分:1)

他们使用Builder模式

以下是 Java

中的示例
/**
 * Represents the product created by the builder.
 */
class Car {
    private int wheels;
    private String color;

    public Car() {
    }

    public String getColor() {
        return color;
    }

    public void setColor(final String color) {
        this.color = color;
    }

    public int getWheels() {
        return wheels;
    }

    public void setWheels(final int wheels) {
        this.wheels = wheels;
    }

    @Override
    public String toString() {
        return "Car [wheels = " + wheels + ", color = " + color + "]";
    }
}

/**
 * The builder abstraction.
 */
interface CarBuilder {
    Car build();

    CarBuilder setColor(final String color);

    CarBuilder setWheels(final int wheels);
}

class CarBuilderImpl implements CarBuilder {
    private Car carTmp;

    public CarBuilderImpl() {
        carTmp = new Car();
    }

    @Override
    public Car build() {
        Car car = new Car();
        car.setColor(carTmp.getColor());
        car.setWheels(carTmp.getWheels());
        return car;
    }

    @Override
    public CarBuilder setColor(final String color) {
        carTmp.setColor(color);
        return this;
    }

    @Override
    public CarBuilder setWheels(final int wheels) {
        carTmp.setWheels(wheels);
        return this;
    }
}

public class CarBuildDirector {
    private CarBuilder builder;

    public CarBuildDirector(final CarBuilder builder) {
        this.builder = builder;
    }

    public Car construct() {
        return builder.setWheels(4)
                      .setColor("Red")
                      .build();
    }

    public static void main(final String[] arguments) {
        final CarBuilder builder = new CarBuilderImpl();

        final CarBuildDirector carBuildDirector = new CarBuildDirector(builder);

        System.out.println(carBuildDirector.construct());
    }
}

答案 1 :(得分:1)

由于您还标记了Kotlin,因此有一个很好的替代方法,Java无法提供。例如。如果您没有AlertDialog.Builder,并且setTitle(title)之类的方法仅在AlertDialog上定义(并且没有return this这样就无法链接),则可以写

val dialog = AlertDialog(...).apply {
    title = "some title" // calls setTitle
    message = "some message"
}

例如https://medium.com/@elye.project/mastering-kotlin-standard-functions-run-with-let-also-and-apply-9cd334b0ef84https://kotlinexpertise.com/coping-with-kotlins-scope-functions/讨论标准范围函数(apply只是其中之一)。

答案 2 :(得分:0)