代理主要具有什么作用?
可以隐藏目标类的具体实现;
可以在不修改目标代码的情况下能够对其功能进行加强。
代码实现
//定义接口
public interface SomeService {
void printMessage();
String toUp();
}
//定义接口实现类
import com.service.SomeService;
public class SomeServiceImpl implements SomeService{
public SomeServiceImpl() {
System.out.println("无参构造执行");
}
@Override
public void printMessage() {
// TODO Auto-generated method stub
System.out.println("SomeServiceImpl.printMessage()方法执行");
}
@Override
public String toUp() {
// TODO Auto-generated method stub
return "xuwei";
}
}
//定义代理对象,实现相同的接口,并进行增强处理
import com.service.SomeService;
public class SomeServiceProxy implements SomeService{
SomeService target;
public SomeServiceProxy(SomeService target) {
super();
this.target = target;
}
public SomeServiceProxy() {
super();
}
public String toUp(){
return target.toUp().toUpperCase();
}
@Override
public void printMessage() {
// TODO Auto-generated method stub
System.out.println("SomeServiceProxy.printMessage()");
}
}
//测试
import com.proxy.SomeServiceProxy;
import com.service.SomeService;
import com.service.impl.SomeServiceImpl;
public class SomeProxyTest {
public static void main(String[] args) {
SomeService ss=new SomeServiceImpl();
SomeService sp=new SomeServiceProxy(ss);
String up = sp.toUp();
System.out.println(up);
sp.printMessage();
}
}