代理模式,时SpringAOP的底层!【SpringAOP和SpringMVC】
代理模式的分类:
生活中的场景:
角色分析:
案例:
package com.massimo.demo;
//租房
public interface Rent {
public void rent();
}
package com.massimo.demo;
//房东
public class Host implements Rent{
public void rent() {
System.out.println("房东要出租房子!");
}
}
package com.massimo.demo;
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
seeHouse();
host.rent();
signIn();
fare();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
//签合同
public void signIn(){
System.out.println("签租赁合同");
}
}
package com.massimo.demo;
public class Client {
public static void main(String[] args) {
//房东要租房子
Host host = new Host();
//代理,中介帮房东租房子,但是,代理角色,这里指中介,会有一些附属操作
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
代理模式的好处:
缺点:
现有如下项目:
package com.massimo.demo2;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
package com.massimo.demo2;
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void query() {
System.out.println("查询了一个用户");
}
}
package com.massimo.demo2;
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
userService.add();
userService.delete();
userService.update();
userService.query();
}
}
效果:
思想:在不改变原有代码的基础上,实现!
package com.massimo.demo2;
public class UserServiceProxy implements UserService {
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.delete();
}
public void update() {
log("update");
userService.update();
}
public void query() {
log("query");
userService.query();
}
//日志方法
public void log(String msg){
System.out.println("使用了" + msg + "方法");
}
}
package com.massimo.demo2;
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setUserService(userService);
proxy.add();
proxy.delete();
proxy.update();
proxy.query();
}
}
效果: