设计模式享元模式

来源:互联网 发布:铁路 纪录片 知乎 编辑:程序博客网 时间:2024/06/05 03:42

转载请注明原创出处,谢谢!

概念:

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。
享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。


上面是很官方的说法,个人理解:在我的理解就是map、list等,或者就是缓存。

JDK 里的享元模式

在 JDK 的设计里,也有很享元模式。比如一些常量池的设计(String 常量池、Integer 常量池等等);
使用缓存来加速大量小对象的访问时间。
- java.lang.Integer#valueOf(int)
- java.lang.Boolean#valueOf(boolean)
- java.lang.Byte#valueOf(byte)
- java.lang.Character#valueOf(char)等等。

备注:http://blog.csdn.net/lirenzuo/article/details/77854990我的这篇里面还提到了Integer问题,感兴趣的可以去看看。

其他场景

  1. 数据库连接池
  2. 线程池等

String类型使用享元模式

public static void main(String[] args) {        String a = "abc";        String b = "abc";        System.out.println(a==b);    }

运行结果:true

Java中将String类定义为final(不可改变的),JVM中字符串一般保存在字符串常量池中,这个字符串常量池在jdk 6.0以前是位于永久代,而在JDK 7.0中,JVM将其从永久代拿出来放置于堆中。
地址:http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern()
 method will see more significant differences.
RFE: 6962931

因为a和b保存的是字符串常量池中的同一个字符串地址。这就类似于我们今天所讲述的享元模式,字符串一旦定义之后就可以被共享使用,因为他们是不可改变的,同时被多处调用也不会存在任何隐患。

总结:

其实本质就是缓存。


个人公众号

匠心零度公众号.jpg