Android中的链式调用

来源:互联网 发布:it狂人类似 编辑:程序博客网 时间:2024/06/05 07:53

引例:

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification notification = new NotificationCompat.Builder(this)    .setContentTitle("this is a content title")    .setContentText("this is a content text")    .setWhen(System.currentTimeMillis())    .setSmallIcon(R.mipmap.ic_launcher)    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))    .build();manager.notify(1, notification);

上述代码片段是 Android 中的 Notification 的基本用法。
现在忽略掉代码片段中的部分参数内容:

Notification notification = new NotificationCompat.Builder(this)    .setContentTitle(...)    .setContentText(...)    .setWhen(...)    .setSmallIcon(...)    .setLargeIcon(...)    .build();

其实这种语法技巧叫做链式调用,在本例中准确来说是链式调用方法链。

按照常规思路,Java 中调用方法的形式 .method() 那么在语法中 . 的前面应该为一个对象,那么我们打开 SDK 源码中的 Notification 类:

/** * Set the first line of text in the platform notification template. */public Builder setContentTitle(CharSequence title) {    mN.extras.putCharSequence(EXTRA_TITLE, safeCharSequence(title));    return this;}/** * Set the second line of text in the platform notification template. */public Builder setContentText(CharSequence text) {     mN.extras.putCharSequence(EXTRA_TEXT, safeCharSequence(text));     return this;}

我们会发现每个方法都返回了一个 this ,return this; 那么问题就解决了,这个 this 代表着对象,所以说每一次调用方法都会返回对象,接着再调用另一个方法。

这种语法技巧在诸多的开源项目中均有用例,如 Glide,这种方式能够使代码更有逻辑,同时使代码看起来更加简洁,对于引例中的 Notification 类,进行调式调用来为其设置各种属性,也能是代码看起来更加清晰紧凑。


简单的例子:

1、一般形式

public class Test {    public static void main(String[] args) {        Person people = new Person();        people.setName("Harry Hacker");        people.setAge(22);        people.setSex("male");    }}class Person {    private String name;    private int age;    private String sex;    public void setAge(int age) {        this.age = age;    }    public void setName(String name) {        this.name = name;    }    public void setSex(String sex) {        this.sex = sex;    }    public int getAge() {        return age;    }    public String getName() {        return name;    }    public String getSex() {        return sex;    }}

2、链式调用

public class Test {    public static void main(String[] args) {        Person people = new Person();        people.setName("Mario jesse")                .setAge(21)                .setSex("female");    }}class Person {    private String name;    private int age;    private String sex;    public Person setAge(int age) {        this.age = age;        return this;    }    public Person setName(String name) {        this.name = name;        return this;    }    public Person setSex(String sex) {        this.sex = sex;        return this;    }    public int getAge() {        return age;    }    public String getName() {        return name;    }    public String getSex() {        return sex;    }}


个人浅见,欢迎指正!

原创粉丝点击