标签:
代理模式:静态代理和动态代理
1.代理类和被代理类必须实现同一个借口
2.代理类和别代理类有一种关联关系
静态代理:
例如实现一个日志:
//定义一个接口
public interface UserDao{
public void delete();
}
//定义一个实现类
public class UserDaoImpl implements UserDao{
public void delete(){
System.out.pritln("成功删除");
}
}
//定义一个代理类
public class LoggingProxy implements UserDao{
Logger logger = Logger.getLogger(this.getClass().getName());
UserDao dao;
public LoggingProxy(UserDao dao){
this.dao = dao;
}
public void delete(){
logger.log(Level.INFO,"删除之前");
dao.delete();
logger.log(Level.INFO,"删除之后");
}
}
//定义一个测试类
public class Test{
public static void main(String args[]){
LoggingProxy proxy = new LoggingProxy (new UserDaoImpl());
proxy.delete();
}
}
弊端:一个代理只能服务于一种类型的对象,系统很大时代理类会很多
动态代理:
//定义一个接口
public interface UserDao{
public void delete();
}
//定义一个实现类
public class UserDaoImpl implements UserDao{
public void delete(){
System.out.pritln("成功删除");
}
}
//定义一个代理类
public class DynamicProxy implements InvocationHandler{//必须实现这个接口
Logger logger = Logger.getLogger(this.getClass().getName());
Object delegate;
//代理类和被代理类的绑定,返回的是目标接口
public Object bind(Object obj){
this.delegate = obj;
Class cls = this.delegate.getClass();
return Proxy.newProxyInstance(cls.getClassLoader(),cls,getInterfaces(),this);
}
//反射机制,动态来调用代理类
public Object invoke(Object proxy,Method method, Object[] args) throws Throwable{
logger.log(Level.INFO,"删除之前");
Object obj = method.invoke(delegate,args);
dao.delete();
logger.log(Level.INFO,"删除之后");
return obj;
}
}
//第二个代理接口
public inteface CustomerDao{
public String update(String username);
}
//第二个代理实现类
public class CustomerDaoImpl implements CustomerDao{
public String update(String username){
System.out.pritln(username+"更新成功");
return "success";
}
}
//定义一个测试类
public class Test{
public static void main(String args[]){
UserDo dao = (UserDao)new DynamicProxy().bind (new UserDaoImpl());
dao.delete();
CustomerDao dao2 = (CustomerDao)new DynamicProxy().bind(new CustomerDaoImpl());
String str = dao2.update("amaker");
System.out.pritln(str);
}
}
标签:
原文地址:http://www.cnblogs.com/hj-lxp/p/5236713.html