import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.junit.Test;
interface 狗{
public void run();
}
public class Dog implements 狗 {
public void run(){
System.out.println("run!!!!!!");
}
//动态代理增强方法
public static void main(String[] args) {
//继承
SuperDog sd=new SuperDog();
sd.run();
//装饰模式
// Dog dog = new Dog();
// BigDog bd=new BigDog(dog);
// bd.run();
//动态代理
// final Dog dog = new Dog();
// 狗 proxyDog = (狗)Proxy.newProxyInstance(dog.getClass().getClassLoader(), dog.getClass().getInterfaces(),
// new InvocationHandler(){
// public Object invoke(Object proxy, Method method, Object[] args)
// throws Throwable {
// if("run".equals(method.getName())){
// System.out.println("Proxy Dog");
// }
// return method.invoke(dog, args);
// }
// });
//
// proxyDog.run();
}
}
//继承方式增前父类的方法
class SuperDog extends Dog{
@Override
public void run() {
System.out.println("SuperDog ");
super.run();
}
}
//装饰模式增强被装饰者的方法
class BigDog implements 狗{
private Dog dog;
public BigDog(Dog dog){
this.dog = dog;
}
public void run() {
System.out.println("BigDog ");
dog.run();
}
}
增强 修改对象的集中方法(继承、装饰者模式、动态代理)
最新推荐文章于 2022-06-03 11:44:04 发布