package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
class Logic{
public void logic(){
Dao dao = Factory.create();
System.out.println("dynamic proxy's name: "+dao.getClass().getName());
dao.insert();
}
}
class Factory{
static Dao create(){
Dao dao = new JdbcDao();
MyInvocationHandler hand = new MyInvocationHandler();
return (Dao)hand.get(dao);
}
}
interface Dao{
public void update();
public void insert();
}
class JdbcDao implements Dao{
public void update(){
System.out.println("in jdbc update");
}
public void insert(){
System.out.println("in jdbc insert");
}
}
class HibernateDao implements Dao{
public void update(){
System.out.println("in hibernate update");
}
public void insert(){
System.out.println("in hibernate insert");
}
}
class MyInvocationHandler implements InvocationHandler {
Object o;
public Object get(Object o){
System.out.println("in get method of MyInvocationHandler");
this.o = o;
return Proxy.newProxyInstance(o.getClass().getClassLoader(),o.getClass().getInterfaces(),this);
}
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
System.out.println("write log before invoke");
Object result = arg1.invoke(o, arg2);
System.out.println("write log after invoke");
return result;
}
}
public class Test {
public static void main(String[] args) {
Logic l = new Logic();
l.logic();
}
}
真么发现代理模式那里好 为什么还要用代理模式
为什么不写一个类 在类中写一个 方法 里面传一个class类型 用那个类就调用哪个类不就得啦 有知道的还请详解啊