01_静态代理

张创琦

方法1:通过extends继承代理

缺点:只能继承自一个父类。继承数量有限

TeamService.java

  1. package com.kkb.service;
  2. public class TeamService {
  3. @Override
  4. public void add(){
  5. System.out.println("TeamService--------add-------");
  6. }
  7. }

ProxyTeamService.java

继承自TeamService.java

  1. package com.kkb.service.staticproxy;
  2. import com.kkb.service.TeamService;
  3. public class ProxyTeamService extends TeamService {
  4. public void add() {
  5. try{
  6. System.out.println("开始事务");
  7. super.add();
  8. System.out.println("提交事务");
  9. } catch(Exception e) {
  10. System.out.println("回滚事务");
  11. }
  12. }
  13. }

test类

  1. public void test02(){
  2. ProxyTeamService proxyTeamService = new ProxyTeamService();
  3. proxyTeamService.add();
  4. }

方法2:通过implements接口代理

2.1:代理类和被代理类实现同一个接口

IService.java

  1. package com.kkb.service;
  2. /**
  3. * 接口定义核心方法
  4. *
  5. */
  6. public interface IService {
  7. void add();
  8. }

UserService.java

  1. package com.kkb.service;
  2. public class UserService implements IService {
  3. @Override
  4. public void add() {
  5. System.out.println("UserService------add------");
  6. }
  7. }

代理类和被代理类实现同一个接口

ProxyTranService.java

  1. package com.kkb.service.staticproxy;
  2. import com.kkb.service.IService;
  3. /**
  4. * 基于接口的静态代理
  5. * 代理类和被代理类实现同一个接口
  6. */
  7. public class ProxyTranService implements IService {
  8. private IService service; //被代理的对象
  9. public ProxyTranService(IService service) {
  10. this.service = service;
  11. }
  12. @Override
  13. public void add() {
  14. try{
  15. System.out.println("开始事务");
  16. service.add();
  17. System.out.println("提交事务");
  18. } catch(Exception e) {
  19. System.out.println("回滚事务");
  20. }
  21. }
  22. }

Test

  1. @Test
  2. public void test03(){
  3. UserService userService = new UserService();
  4. ProxyTranService tranService = new ProxyTranService(userService);//一级代理
  5. tranService.add();
  6. }

2.2:多级代理模式

ProxyLogService.java

  1. package com.kkb.service.staticproxy;
  2. import com.kkb.service.IService;
  3. public class ProxyLogService implements IService {
  4. private IService service;
  5. public ProxyLogService(IService service) {
  6. this.service = service;
  7. }
  8. @Override
  9. public void add() {
  10. try{
  11. System.out.println("开始日志");
  12. service.add();
  13. System.out.println("结束日志");
  14. } catch(Exception e) {
  15. System.out.println("异常日志");
  16. }
  17. }
  18. }

Test

  1. public static void main(String[] args) {
  2. UserService userService = new UserService();
  3. ProxyTranService tranService = new ProxyTranService(userService);//一级代理
  4. ProxyLogService logService = new ProxyLogService(tranService);//二级代理
  5. logService.add();
  6. }