类图
实现
调用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
GeneralClass general = new GeneralClass();
general.doIt();
System.out.println("++++++++++++++++++++");
GeneralClass elephant = new ElephantClass();
elephant.doIt();
System.out.println("++++++++++++++++++++");
GeneralClass apple = new AppleClass();
apple.doIt();
}
}
输出
把冰箱门打开
把某东西装进去
把冰箱门带上
++++++++++++++++++++
把冰箱门打开
把大象装进去
把冰箱门带上
++++++++++++++++++++
把冰箱门打开
把苹果装进去
把冰箱门带上
Process finished with exit code 0
把某东西装进冰箱的类
package com.company;
/**
* 把某东西装冰箱
*/
public class GeneralClass {
protected void openFridge() {
System.out.println("把冰箱门打开");
}
protected void closeFridge() {
System.out.println("把冰箱门带上");
}
protected void putSomethingIn() {
System.out.println("把某东西装进去");
}
/**
* 这个就是那个hook方法。
* 在这里我不重写它,所此处用final修饰。
*/
public final void doIt() {
this.openFridge();
this.putSomethingIn();
this.closeFridge();
}
}
把大象装冰箱
package com.company;
public class ElephantClass extends GeneralClass {
@Override
protected void putSomethingIn() {
System.out.println("把大象装进去");
}
}
把苹果装冰箱
package com.company;
public class AppleClass extends GeneralClass {
@Override
protected void putSomethingIn() {
System.out.println("把苹果装进去");
}
}