码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 设计模式——享元模式(Flyweight Pattern)+ Spring相关源码


    文章目录

    • 一、享元模式定义
    • 二、例子
      • 2.1 菜鸟教程例子
        • 2.1.1 定义被缓存对象
        • 2.1.2 定义ShapeFactory
      • 2.2 JDK源码——Integer
      • 2.3 JDK源码——DriverManager
      • 2.4 Spring源码——HandlerMethodArgumentResolverComposite
      • 除此之外BeanFactory获取bean其实也是一种享元模式的应用。
    • 三、其他设计模式

    一、享元模式定义

    类型: 结构型模式
    介绍: 使用容器(数组、集合等…)缓存常用对象。它也是池技术的重要实现方式,正如常量池、数据库连接池、缓冲池等都是享元模式的应用。
    目的: 主要用于减少 频繁创建对象带来的开销。

    二、例子

    2.1 菜鸟教程例子

    2.1.1 定义被缓存对象

    public class Circle {
       private String color;
     
       public Circle(String color){
          this.color = color;     
       }
       public void draw() {
          System.out.println("Circle: Draw()");
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.1.2 定义ShapeFactory

    ShapeFactory用HashMap缓存Circle对象。

    import java.util.HashMap;
     
    public class ShapeFactory {
       private static final HashMap<String, Shape> circleMap = new HashMap<>();
     
       public static Shape getCircle(String color) {
          Circle circle = (Circle)circleMap.get(color);
     
          if(circle == null) {
             circle = new Circle(color);
             circleMap.put(color, circle);
             System.out.println("Creating circle of color : " + color);
          }
          return circle;
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2.2 JDK源码——Integer

    -128~127会去IntegerCache里获取

    public final class Integer extends Number implements Comparable<Integer>, Constable, ConstantDesc {
    
    	@IntrinsicCandidate
        public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    缓存池IntegerCache

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;
    
        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    h = Math.max(parseInt(integerCacheHighPropValue), 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
    
            // Load IntegerCache.archivedCache from archive, if possible
            CDS.initializeFromArchive(IntegerCache.class);
            int size = (high - low) + 1;
    
            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }
    
        private IntegerCache() {}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    2.3 JDK源码——DriverManager

    CopyOnWriteArrayList registeredDrivers 缓存DriverInfo对象。

    public class DriverManager {
    
    
        // List of registered JDBC drivers
        private static final CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();
        
    	public static Connection getConnection(String url, java.util.Properties info) throws SQLException {
            return (getConnection(url, info, Reflection.getCallerClass()));
        }
    	
    	 @CallerSensitiveAdapter
        private static Connection getConnection(
            String url, java.util.Properties info, Class<?> caller) throws SQLException {
            /*
             * When callerCl is null, we should check the application's
             * (which is invoking this class indirectly)
             * classloader, so that the JDBC driver class outside rt.jar
             * can be loaded from here.
             */
            ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
            if (callerCL == null || callerCL == ClassLoader.getPlatformClassLoader()) {
                callerCL = Thread.currentThread().getContextClassLoader();
            }
    
            if (url == null) {
                throw new SQLException("The url cannot be null", "08001");
            }
    
            println("DriverManager.getConnection(\"" + url + "\")");
    
            ensureDriversInitialized();
    
            // Walk through the loaded registeredDrivers attempting to make a connection.
            // Remember the first exception that gets raised so we can reraise it.
            SQLException reason = null;
    
            for (DriverInfo aDriver : registeredDrivers) {
                // If the caller does not have permission to load the driver then
                // skip it.
                if (isDriverAllowed(aDriver.driver, callerCL)) {
                    try {
                        println("    trying " + aDriver.driver.getClass().getName());
                        Connection con = aDriver.driver.connect(url, info);
                        if (con != null) {
                            // Success!
                            println("getConnection returning " + aDriver.driver.getClass().getName());
                            return (con);
                        }
                    } catch (SQLException ex) {
                        if (reason == null) {
                            reason = ex;
                        }
                    }
    
                } else {
                    println("    skipping: " + aDriver.driver.getClass().getName());
                }
    
            }
    
            // if we got here nobody could connect.
            if (reason != null)    {
                println("getConnection failed: " + reason);
                throw reason;
            }
    
            println("getConnection: no suitable driver found for "+ url);
            throw new SQLException("No suitable driver found for "+ url, "08001");
        }
    
    }
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    2.4 Spring源码——HandlerMethodArgumentResolverComposite

    public class HandlerMethodArgumentResolverComposite implements HandlerMethodArgumentResolver {
    
       private final List<HandlerMethodArgumentResolver> argumentResolvers = new LinkedList<>();
    
       private final Map<MethodParameter, HandlerMethodArgumentResolver> argumentResolverCache = new ConcurrentHashMap<>(256);
       
        @Nullable
        private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
            HandlerMethodArgumentResolver result = (HandlerMethodArgumentResolver)this.argumentResolverCache.get(parameter);
            if (result == null) {
                Iterator var3 = this.argumentResolvers.iterator();
    
                while(var3.hasNext()) {
                    HandlerMethodArgumentResolver resolver = (HandlerMethodArgumentResolver)var3.next();
                    if (resolver.supportsParameter(parameter)) {
                        result = resolver;
                        this.argumentResolverCache.put(parameter, resolver);
                        break;
                    }
                }
            }
    
            return result;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    除此之外BeanFactory获取bean其实也是一种享元模式的应用。

    三、其他设计模式

    创建型模式
    结构型模式

    • 1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码

    行为型模式

    • 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
    • 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
    • 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
    • 4、设计模式——状态模式(State Pattern)
    • 5、设计模式——命令模式(Command Pattern)+ Spring相关源码
    • 6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码
    • 7、设计模式——备忘录模式(Memento Pattern)
    • 8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码
    • 9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码
    • 10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码
    • 11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码
  • 相关阅读:
    gdb调试
    BaseException 工具类
    js获取当前时间
    Win11显示麦克风未插上怎么办?
    消息推送平台终于要发布啦!
    史上最详细的hadoop安装教程
    美国NSC大规模数据泄露,涉及壳牌、戴尔、特斯拉等2000多家公司
    计算机基础理论笔试题
    Linux 服务器使用过程中,mysql突然不能用了,报如下错误
    CSCA08H Assignment 3: Hypertension and Low Income in Toronto Neighbourhoods
  • 原文地址:https://blog.csdn.net/malu_record/article/details/134278684
  • 最新文章
  • 【JVM】编译执行与解释执行的区别是什么?JVM 使用哪种方式?
    用 Hashids 优雅解决 C 端自增 ID 暴露问题
    V8引擎 精品漫游指南--Ignition篇(上) 指令 栈帧 槽位 调用约定 内存布局 基础内容
    LLVM Pass快速入门(四):代码插桩
    milkup:桌面端 markdown AI续写和即时渲染
    基于项目工程构建SBOM(软件物料清单)的研究
    鸿蒙应用开发UI基础第二节:鸿蒙应用程序框架核心解析与实操
    .NET 中如何快速实现 List 集合去重?
    扣子Coze实战:从0到1打造抖音+小红书热点监控智能体
    浅谈数据访问层
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
小工具 小游戏
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1

京公网安备 11010502049817号