代理模式 —— 静态代理模式

      1. 负责声明新增功能
      2. 代替开发人员完成目标方法与新增功能的调用

目标方法调用

开发人员==>切面类对象==》

新增功能调用

  1. 口号
    1. 一个切面类为一个接口服务
优缺点
  1. 优点
    1. 在不违反开闭原则,不产生重复性编码的情况下,将新增功能与目标方法进行关联
    2. 第一次将代理模式角色进行了清晰划分
    3. 明确一个切面类为一个接口服务的------------面向接口编程
  1. 缺点
    1. 后期目标类个数发生变化时,要帮助的目标方法发生变化时,都会导致提供帮助的切面类进行二次维护------------------切面类后期维护会过于频繁
演示
接口
复制代码
public interface BaseService {
    void run();
}
目标类
复制代码
public class Service1 implements BaseService {
    @Override
    public void run() {
        System.out.println("Service1运行");
    }
}

public class Service2 implements BaseService {
    @Override
    public void run() {
        System.out.println("Service2运行");
    }
}
切面类
复制代码
public class ServiceAspect {
    private BaseService target;

    /**
     * 输出当前时间
     */
    public void getTime(){
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        System.out.println("运行结束的时间:" + date);
    }

    /**
     *
     * @param i 区分类的id
     */
    public void invoke(int i){
        if (i == 1) {
            target = new Service1();
        }
        if (i == 2) {
            target = new Service2();
        }
        target.run();
        getTime();
    }
}
测试类
复制代码
public class ServiceAspectTest {
    @Test
    public void getTimeTest(){
        ServiceAspect serviceAspect = new ServiceAspect();
        serviceAspect.invoke(1);
        /*
        Service1运行
        运行结束的时间:2024-03-27 20:30:20
        * */
        serviceAspect.invoke(2);
        /*
        Service2运行
        运行结束的时间:2024-03-27 20:30:20
        * */
    }
}
相关推荐
wuqingshun3141591 天前
什么是代理模式?一般用在什么场景?
java·mysql·代理模式
我登哥MVP1 天前
走进 Gang of Four 设计模式:代理模式
设计模式·代理模式
折哥的程序人生 · 物流技术专研3 天前
Java 23 种设计模式:从踩坑到精通 | 番外:代理 vs 装饰器 —— Spring AOP 到底用了哪个?
java·代理模式·装饰器模式·java面试·java设计模式·springaop·从踩坑到精通
初学者,亦行者4 天前
算法设计与分析3:贪心法 - 求解最短路径问题(TSP)
算法·代理模式
2501_916007477 天前
iPad 怎么抓包 从代理模式到暴力抓包的操作方法
android·ios·小程序·uni-app·代理模式·iphone·ipad
越甲八千7 天前
代理模式和适配器模式区别
代理模式·适配器模式
AI人工智能+电脑小能手11 天前
【大白话说Java面试题 第156题】【06_Spring篇】第16题:Spring 用到了哪些设计模式?
java·spring·设计模式·代理模式·工厂模式
许彰午1 个月前
36_Java设计模式之代理模式
java·设计模式·代理模式
devilnumber1 个月前
静态代理 & 动态代理:实战运用 + 场景区别 + 怎么选
java·开发语言·代理模式
devilnumber1 个月前
想真正吃透 + 灵活运用 Java 代理模式
java·开发语言·代理模式