• Java链式编程接口


    在android开发中显示一个AlertDialog时,常采用下列的写法:

    new AlertDialog.Builder(getApplicationContext())
            .setTitle("Dialog")
            .setMessage("Link program")
            .setPositiveButton("OK", new OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //TODO
                    
                }
            })
            .show();

    可以注意到setTitle/setMessage/setPositiveButton等接口都是直接紧接着执行,用点号隔开,这样的方法叫做链式编程。

    观看setTitle,setMessage等源码会发现,每个方法(接口)的返回值都是AlertDialog.Builder类型,所以秘诀在于方法的返回值类型都必须与第一个点号前面的类型保持一致:

    /**
             * Set the title displayed in the {@link Dialog}.
             *
             * @return This Builder object to allow for chaining of calls to set methods
             */
            public Builder setTitle(CharSequence title) {
                P.mTitle = title;
                return this;
            }
    
    /**
             * Set the message to display.
              *
             * @return This Builder object to allow for chaining of calls to set methods
             */
            public Builder setMessage(CharSequence message) {
                P.mMessage = message;
                return this;
            }

    这样写法的好处在于一方面可以尽可能少去进行类型转换的判定,而且大大增强了代码的阅读性,同时也减少了代码量。

    下面通过一个小例子来演示如何制作这样的链式编程接口

    public class LinkProgram {
    
        private String mText;
        private int mId;
        private boolean isAdd;
        
        public static void main(String[] args) {
    
            LinkProgram link = new LinkProgram();
            
            //链式接口调用时,返回值类型和link该对象类型保持一致
            link.setAdd(true)
                .setId(5)
                .setText("hello world");
            
            System.out.println(link);
    
        }
        
        @Override
        public String toString() {
            return "Text:" + mText + ", Id:" + mId + ", add:" + isAdd;
        }
    
        //返回值类型为LinkProgram
        public LinkProgram setText(String mText) {
            this.mText = mText;
            return this;
        }
    
        //返回值类型为LinkProgram
        public LinkProgram setId(int mId) {
            this.mId = mId;
            return this;
        }
    
        //返回值类型为LinkProgram
        public LinkProgram setAdd(boolean isAdd) {
            this.isAdd = isAdd;
            return this;
        }
        
    }

    运行结果:
    Text:hello world, Id:5, add:true

  • 相关阅读:
    ATM演示
    Java类集框架之LinkedList源码剖析
    字节流
    查询信息的服务器 客户端设立 支持并发多线程
    Java I/O
    java 一道多线程的题
    java面向对象
    入门IT
    解决loadrunner录制时 Request Connection: Remote Server @ 0.0.0.0:80 (Service=?) NOT PROXIED! (REASON: Unable to connect to remote server: rc = -1 , le = 0)问题
    可用于测试的接口(网上搜集自行甄别)
  • 原文地址:https://www.cnblogs.com/soaringEveryday/p/4435563.html
Copyright © 2020-2023  润新知