首页 > 技术文章 > java 连缀用法

deltadeblog 原文

连缀用法,即是在实例化对象时,同时为对象的属性设值。

如示例所示,在创建对象时,同时调用属性的设值函数,为属性赋值

        Apple apple = new Apple()
                .setColor("Green")
                .setWeight(12.3f);

实现方法是,每个设值函数都返回this

public class Apple {

    private String color;
    public Apple setColor(String color) {
        this.color = color;
        return this;
        }
    public String getColor() {return color;}

    private float weight;
    public Apple setWeight(float weight) {
        this.weight = weight;
        return this;
        }
    public float getWeight() {return weight;}

}

推荐阅读