父类:返回值是泛型;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Helper<T extends Helper> {
protected T child;
public Helper() {
child = (T) this;
}
public T setText(@IdRes int viewId,String textStr) {
...
checkChild();
return child;
}
protected void checkChild() {
if (child == null)
throw new IllegalStateException("child must be set in child's Constructor!" +
"not method:initDefaultValueAnimator");
}
}

子类:制定泛型 + 继承父类

  • 光继承,就已经包含扩展能力了。
  • warpper方法其实装饰器模式

    用到的地方:例如一个方法的参数是Helper类型,并且无法改变参数的类型。继而用装饰器扩展其功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ExtraHelper<T extends ExtraHelper> extends Helper<T> {


protected ExtraHelper(Helper helper) {
super(helper.getContext(), helper.getHolder(), helper.getAdapter());
child = (T) this;
}

public static ExtraHelper<ExtraHelper> wrapper(Helper helper) {
return new ExtraHelper(helper);
}

public T heihei() {
System.out.println("heihei!");
checkChild();
return child;
}

public T heihei2() {
System.out.println("heihei2!");
checkChild();
return child;
}
}

最后的使用

1
ExtraHelper.wrapper(helper).setText(R.id.tv, data).heihei().heihei2()

Demo
Demo2