动态代理方法:
代码实现:
package kkk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface IMessage {
public void send() ;
}
class MessageReal implements IMessage {
@Override
public void send() {
// TODO Auto-generated method stub
System.out.println("【发送消息】www.baidu.cn") ;
}
}
class MLDNProxy implements InvocationHandler {
private Object target ;
public Object bind(Object target) {
this.target = target ;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this) ;
}
public boolean connect() {
System.out.println("【消息代理】进行消息发送通道的连接。");
return true ;
}
public void close() {
System.out.println("【消息代理】关闭消息通道。");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object returnData = null ;
if(this.connect()){
returnData = method.invoke(this.target, args) ;
this.close();
}
return returnData;
}
}
public class ll {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
IMessage iMessage = (IMessage) new MLDNProxy().bind(new MessageReal()) ;
iMessage.send();
}
}
Annotation整合工厂设计模式与代理设计模式:
package kkk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface IMessage {
public void send(String msg) ;
}
class MessageService {
private IMessage message ;
public MessageService() {
this.message = Factory.getInstance(MessageImpl.class) ;
}
public void send(String msg){
this.message.send(msg);
}
}
class Factory {
private Factory() {}
public static <T> T getInstance(Class<T> clazz) { //直接返回一个实例化对象
try {
return (T) new MessageProxy().bind(clazz.getDeclaredConstructor().newInstance()) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null ;
}
}
}
class MessageProxy implements InvocationHandler {
private Object target ;
public Object bind(Object target) {
this.target = target ;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this) ;
}
public boolean connect() {
System.out.println("【代理操作】进行消息发送通道的连接。") ;
return true ;
}
public void close() {
System.out.println("【代理操作】关闭连接通道。") ;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
try{
if(this.connect()){
return method.invoke(this.target,args);
}else {
throw new Exception("【Error】消息无法进行发送。") ;
}
}finally {
this.close();
}
}
}
class MessageImpl implements IMessage {
@Override
public void send(String msg) {
// TODO Auto-generated method stub
System.out.println("【消息发送】" + msg );
}
}
public class ll {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
MessageService messageService = new MessageService();
messageService.send("www.baidu.cn");
}
}