Hook卡隼函数
package cn.pw.java.dp.hook;
public class HookMain {
static void job(Person ps) {
System.out.println("job: " + ps.hook());
}
public static void main(String[] args) {
Manager peter = new Manager("Android");
Engineer alvin = new Engineer("Android");
Engineer lily = new Engineer("IOS");
job(peter);
job(alvin);
job(lily);
}
}
//framework
abstract class Person {
protected String skill;
public Person(String a) {
skill = a;
}
//hook函数
public abstract String hook();
}
// APP
class Engineer extends Person {
public Engineer(String a) {
super(a);
}
public String hook() {
return skill+" Engineer";
}
}
// APP
class Manager extends Person {
public Manager(String a) {
super(a);
}
public String hook() {
return skill + " Manager";
}
}
Template Method(继承+Hook卡隼)
目标:将变与不变分离,变化部分由子类(AP应用)编写hook(),不变部分由父类(AF应用框架)完成并关联待子类实现的hook。
UML图中: AbstractClass(AF)中templateMethod()的不变方法 调用SubClass(AP)实现primitive1(),2()的变化方法。
package cn.pw.java.dp.templatemethod;
//***** 1.分析变(变量string,int)与不变( 方法print )
class A{
String a;
public A(String x) {
a = x;
}
public void print(){
System.out.println(a);
}
}
class B{
int b;
public B(int x) {
b = x;
}
public void print(){
System.out.println(b);
}
}
//***** 2.将变的部分写入到hook函数中
class AA{
String a;
public AA(String x) {
a = x;
}
public String hook() {
return a;
}
public void print(){
System.out.println(hook());
}
}
class BB{
int b;
public BB(int x) {
b = x;
}
public String hook() {
return String.valueOf(b);
}
public void print(){
System.out.println(hook());
}
}
//***** 3.将不变部分放在抽象类中,关联hook()
abstract class SuperAB{
abstract String hook();
public void print() {
System.out.println(hook());
}
}
class AAA extends SuperAB{
String a;
public AAA(String x) {
a = x;
}
@Override
public String hook() {
return a;
}
}
class BBB extends SuperAB{
int b;
public BBB(int x) {
b = x;
}
@Override
public String hook() {
return String.valueOf(b);
}
}
public class TemplateMethodMain {
public static void main(String[] args) {
SuperAB a = new AAA("xxx");
a.print();
}
}
Android中常见应用场景
Android中类似应用:变化部分实现子类复写 如onXXX(),由AF调用。
View中 : draw() -> onDraw() layout() -> onLayout()、 measure -> onMeasure()
Binder中:transact -> onTransact().