链式编程(Java写法)

链式编程(Java写法) 

在我们编写代码过程中听到过很多说法
如:面向切面编程,函数式编程,面向对象编程,泛式编程等等
接着我来说下链式编程
普通:
  1:维护性强
  2:对方法的返回类型无要求
  3:对程序员的业务要求适中
链式:
  1:编程性强
  2:可读性强
  3:代码简洁
  4:对程序员的业务能力要求高
  5:不太利于代码调试
  在java中StringBuilder已经实现了链式的写法
  

StringBuilder builder = new StringBuilder();
        builder.append("blake").append("bob").append("alice").append("linese").append("eve");
  •  是不是很方便呢!

怎么实现呢,其实就是在设置的返回当前的对象
jdk StringBuilder的写法

@Override
    public StringBuilder append(String str) {
        super.append(str);
        return this;
    }
  •  

试着按这种方法一个例子如下:

public class Apple {
    private double height;
    private String color;
    private boolean flag;

    public double getHeight() {
        return height;
    }

    public Apple setHeight(double height) {
        this.height = height;
        return this;// return 当前对象
    }

    public String getColor() {
        return color;
    }

    public Apple setColor(String color) {
        this.color = color;
        return this;// return 当前对象
    }

    public boolean isFlag() {
        return flag;
    }

    public Apple setFlag(boolean flag) {
        this.flag = flag;
        return this;// return 当前对象
    }

    public Apple() {
    }

    @Override
    public String toString() {
        return "Apple{" +
                "height=" + height +
                ", color='" + color + '\'' +
                ", flag=" + flag +
                '}';
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    public static void main(String[] args) {
        Apple apple = new Apple();
        apple.setColor("red").setFlag(true).setHeight(22.56);//链式
        System.out.println(apple);
    }
}
  •  

打印结果如下:

Apple{height=22.56, color='red', flag=true}
  •  

结果如我们预料中的一样

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值