JAVA 代理方式实现接口实例化,WebService的方式实现远程方法调用

本文介绍了一个基于Java的接口工厂设计模式实现,通过抽象类和代理模式来动态创建接口实例,并支持远程方法调用。该模式简化了WebService的远程调用过程。
接口工厂
/**
* <pre>
* Title: 接口工厂
* </pre>
*/
public abstract class AbstractInterfaceFactory {
protected static final Logger logger = Logger
.getLogger(AbstractInterfaceFactory.class.getName());

public static AbstractInterfaceFactory getInstance(){
return new DefaultInterfaceFactory();
}


/** 私有化, */
protected AbstractInterfaceFactory(){}


public <T> T getWebService(Class<T> oldInterface) {
InterfaceHandler intr = new InterfaceHandler(this);

Object bufferedInter = Proxy.newProxyInstance(getClass()
.getClassLoader(), new Class[] { oldInterface }, intr);

return (T) bufferedInter;
}

/** 子类实现 */
protected abstract Object remoteCall(String methodName, Object[] args);

/** 代理类 */
private static final class InterfaceHandler implements InvocationHandler {
private AbstractInterfaceFactory factory;

public InterfaceHandler(AbstractInterfaceFactory factory) {
this.factory = factory;
}


public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String remoteMethodName = method.getName();
logger.info("开始调用接口:" + remoteMethodName);

Object rst = factory.remoteCall(remoteMethodName, args);

logger.info("完成调用");
return rst;
}

}

/** 静态工厂的默认实现 */
private static final class DefaultInterfaceFactory extends AbstractInterfaceFactory {
protected Object remoteCall(String methodName, Object[] args) {
logger.info("远程方法调用中.....");
return methodName;
}
}
}


实际接口
/**
*
* <pre>
* Title: 任意定义的两个接口
* </pre>
*/
public interface MyInterface {
public String getVersion();

public String doJob();
}


测试类
public class testInterfaceFactory {
public static void main(String[] args) {
AbstractInterfaceFactory factory = AbstractInterfaceFactory.getInstance();
MyInterface intr = factory.getWebService(MyInterface.class);
System.out.println("获取版本:" + intr.getVersion());

intr = factory.getWebService(MyInterface.class);
System.out.println("doJob:" + intr.doJob());
}
}


运用:远程调用WebService时,可以考虑使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值