美文网首页
链式编程(Java写法)

链式编程(Java写法)

作者: 海边的蜗牛ng | 来源:发表于2018-06-17 16:14 被阅读0次

    在我们编写代码过程中听到过很多说法
    如:面向切面编程,函数式编程,面向对象编程,泛式编程等等
    接着我来说下链式编程
    普通:
      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}
    

    结果如我们预料中的一样

    相关文章

      网友评论

          本文标题:链式编程(Java写法)

          本文链接:https://www.haomeiwen.com/subject/umpweftx.html