01_静态代理
张创琦
方法1:通过extends继承代理
缺点:只能继承自一个父类。继承数量有限
TeamService.java
package com.kkb.service;
public class TeamService {
@Override
public void add(){
System.out.println("TeamService--------add-------");
}
}
ProxyTeamService.java
继承自TeamService.java
package com.kkb.service.staticproxy;
import com.kkb.service.TeamService;
public class ProxyTeamService extends TeamService {
public void add() {
try{
System.out.println("开始事务");
super.add();
System.out.println("提交事务");
} catch(Exception e) {
System.out.println("回滚事务");
}
}
}
test类
public void test02(){
ProxyTeamService proxyTeamService = new ProxyTeamService();
proxyTeamService.add();
}
方法2:通过implements接口代理
2.1:代理类和被代理类实现同一个接口
IService.java
package com.kkb.service;
/**
* 接口定义核心方法
*
*/
public interface IService {
void add();
}
UserService.java
package com.kkb.service;
public class UserService implements IService {
@Override
public void add() {
System.out.println("UserService------add------");
}
}
代理类和被代理类实现同一个接口
ProxyTranService.java
package com.kkb.service.staticproxy;
import com.kkb.service.IService;
/**
* 基于接口的静态代理
* 代理类和被代理类实现同一个接口
*/
public class ProxyTranService implements IService {
private IService service; //被代理的对象
public ProxyTranService(IService service) {
this.service = service;
}
@Override
public void add() {
try{
System.out.println("开始事务");
service.add();
System.out.println("提交事务");
} catch(Exception e) {
System.out.println("回滚事务");
}
}
}
Test
@Test
public void test03(){
UserService userService = new UserService();
ProxyTranService tranService = new ProxyTranService(userService);//一级代理
tranService.add();
}
2.2:多级代理模式
ProxyLogService.java
package com.kkb.service.staticproxy;
import com.kkb.service.IService;
public class ProxyLogService implements IService {
private IService service;
public ProxyLogService(IService service) {
this.service = service;
}
@Override
public void add() {
try{
System.out.println("开始日志");
service.add();
System.out.println("结束日志");
} catch(Exception e) {
System.out.println("异常日志");
}
}
}
Test
public static void main(String[] args) {
UserService userService = new UserService();
ProxyTranService tranService = new ProxyTranService(userService);//一级代理
ProxyLogService logService = new ProxyLogService(tranService);//二级代理
logService.add();
}