Java静态代理总结
总结:
- 真实对象(被代理对象)和代理对象都要实现同一个接口
- 代理对象要代理真实角色(被代理对象)
优点:
- 代理对象可以补充真实对象(被代理对象)所要做的事情
- 真实对象(被代理对象)只需要关注自己做的事情
// 被代理的接口
interface Study {
void readBook();
}
// 真实对象(被代理对象)
class You implements Study {
@Override
public void readBook() {
System.out.println("I like Studing!");
}
}
// 代理类
class School implements Study {
// 真实对象类(被代理对象)
private Study target;
public School(Study target) {
this.target = target;
}
@Override
public void readBook() {
before();
this.target.readBook();
after();
}
private void before() {
System.out.println("buy books.");
}
private void after() {
System.out.println("supply foods.");
}
}
public class StacticProxy {
public static void main(String[] args) {
// 传入真实对象类(被代理对象)给代理类
School School = new School(new You());
School.readBook();
}
}
执行结果:
静态代理实现打日志功能
- 被代理的接口
public interface ActionService {
String add();
String query();
String delete();
String update();
}
- 被代理类
public class ActionServiceImpl implements ActionService {
@Override
public String add() {
return "add";
}
@Override
public String query() {
return "query";
}
@Override
public String delete() {
return "delete";
}
@Override
public String update() {
return "update";
}
}
- 代理类
package com.wcj.proxy;
import com.wcj.service.ActionService;
import com.wcj.service.impl.ActionServiceImpl;
public class ActionProxyService implements ActionService {
private ActionServiceImpl actionService;
public ActionProxyService(ActionServiceImpl actionService) {
this.actionService = actionService;
}
@Override
public String add() {
System.out.println("====>add");
return actionService.add();
}
@Override
public String query() {
System.out.println("====>query");
return actionService.query();
}
@Override
public String delete() {
System.out.println("====>delete");
return actionService.delete();
}
@Override
public String update() {
System.out.println("====>update");
return actionService.update();
}
}
- 测试方法
public class testProxy {
public static void main(String[] args) {
ActionServiceImpl actionService = new ActionServiceImpl();
ActionProxyService actionProxyService = new ActionProxyService(actionService);
actionProxyService.add();
actionProxyService.delete();
actionProxyService.update();
actionProxyService.query();
}
}
- 测试结果