package com.gyarmy.datesource; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.junit.Test; public class TestData1 { @Test public void test1(){ System.out.println("test1"); //继承 Cat car1 = new Cat(){ @Override public void run(){ System.out.println("cat 100"); super.run(); } }; car1.run(); //装饰设计模式 } @Test public void test2(){ DecractorCat dCat = new DecractorCat(new Cat()); dCat.run(); } @Test public void test3(){ final ICat cat = new Cat(); ICat proxyCat = (ICat)Proxy.newProxyInstance(Cat.class.getClassLoader(), cat.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub //System.out.println("www.gyarmy.com"); if(method.getName().equalsIgnoreCase("run")){ System.out.println("折耳猫 跑步"); } if(method.getName().equalsIgnoreCase("eat")){ System.out.println("折耳猫 吃饭"); //调用底层方法 return method.invoke(cat, args); } //调用原有的方法 return method.invoke(cat, args); } }); proxyCat.eat(); System.out.println(proxyCat.hashCode()); } } class DecractorCat implements ICat{ private ICat cat; public DecractorCat(ICat cat){ this.cat = cat; } @Override public void run() { // TODO Auto-generated method stub //方法加强 System.out.println("加菲猫 跑步"); cat.run(); } @Override public void eat() { // TODO Auto-generated method stub System.out.println("加菲猫 吃饭"); cat.run(); } } class Cat implements ICat{ public void run(){ System.out.println("猫跑步"); } public void eat(){ System.out.println("猫 吃饭"); } } interface ICat{ public void run(); public void eat(); }
0则评论给“java中方法加强的3中方法”