最近我一直在学习如何在Android中构建通知,我遇到过这个问题:
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.test_image)
.setLargeIcon(largeIcon)
.setContentTitle("Notification Compat")
.setContentText("Notification area -->
Modifiable!").setNumber(num);
无论我如何编写代码,结果都是一样的。 即例如,如果我改变顺序,则在setContentTitle()之前调用setContentText()。它返回相同的Notification Builder对象。 代码:
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.test_image)
.setLargeIcon(largeIcon)
.setContentText("Notification area --> Modifiable!") // Modification
.setContentTitle("Notification Compat").setNumber(num);
谁能告诉我这怎么可能? 谢谢。
答案 0 :(得分:1)
Here是如何创建Builder pattern
的示例。
示例强>
public class FooBar {
private int mA, mB;
private FooBar(int a, int b) {
this.mA = a;
this.mB = b;
}
public int getA() {
return mA;
}
public void setA(int a) {
this.mA = a;
}
public int getB() {
return mB;
}
public void setB(int b) {
this.mB = b;
}
public static class FooBarBuilder {
private int mNestedA, mNestedB;
public FooBarBuilder() {
this.mNestedA = 0;
this.mNestedB = 0;
}
public FooBarBuilder(int nestedA, int nestedB) {
this.mNestedA = nestedA;
this.mNestedB = nestedB;
}
public int getNestedA() {
return mNestedA;
}
public FooBarBuilder setNestedA(int nestedA) {
this.mNestedA = nestedA;
return this;
}
public int getNestedB() {
return mNestedB;
}
public FooBarBuilder setNestedB(int nestedB) {
this.mNestedB = nestedB;
return this;
}
public FooBar create() {
return new FooBar(mNestedA, mNestedB);
}
}
}
答案 1 :(得分:0)
这是一个Builder模式。每次调用Builder的方法时,它都会设置一些作为参数传递的值,并返回相同的Builder对象。所以顺序无关紧要。如果在不返回对象的情况下调用setters方法,则相同。 Builder的示例代码:
public class Builder {
String mTitle;
int mCount;
public Builder setTitle(String title) {
mTitle = title;
return this;
}
public Builder setCount(int count) {
mCount = count;
return this;
}
}
用法:
Builder builder = new Builder()
.setTitle("Some title")
.setCount(count);