java 的静态代理和动态代理

静态代理:客户,中介,房东租房场景的例子:

//抽象的接口类

package cn.thomson.proxy;

public interface rent {

public void rent();

}

//房东出租此屋

package cn.thomson.proxy;

public class Host implements rent {
  public void rent(){
 System.out.println("出租此屋");

  }

//中介租屋

package cn.thomson.proxy;
public class Proxy implements rent{
    private  Host host;
    public Proxy(Host host) {
this.host=host;
}
public void rent(){
seeHouse();
    host.rent();
    getMoney();    
    }    
public void seeHouse(){
System.out.println("参观此屋");
}
public void getMoney(){
System.out.println("收取中介费");
}

}

租房客户(测试类)

package cn.thomson.proxy;
public class Customer {
public static void main(String[] args) {
Host host=new Host();
Proxy proxy=new Proxy(host);
        proxy.rent();
}

}

中介只具有参观此屋和收取中介费的功能。但是打印信息如下:


此为静态代理模式。代理和代理对象实现相同的抽象方法。

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

动态代理模式:

//抽象类

package ProxyFactory;

public interface IUserDao {

 void save();

}

//实现抽象方法

package ProxyFactory;
public class UserDao implements IUserDao {
@Override
public void save() {
// TODO Auto-generated method stub
System.out.println("已经保存数据");
}

}

//代理类

package ProxyFactory;

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;
public class proxyFactory {
//目标对象
private  Object target;
public proxyFactory(Object target) {
super();
this.target = target;
}
//目标对象和代理对象关联
    public Object getInstance(){
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(“事物1”);

Object obj=method.invoke(target, args);

                           System.out.println(“事物2”);

return obj;          

}});    
    }
}

//测试类

package ProxyFactory;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//目标对象
IUserDao target=new UserDao();
IUserDao proxy=(IUserDao)new proxyFactory(target).getInstance();
proxy.save();
}

}

测试结果为:


阅读更多

没有更多推荐了,返回首页