1.适用场景:主要用于减少创建对象的数量,尝试重用现有的同类对象,只有当未找到匹配的对象,则创建新对象。
2.示例:java中的String类为典型的享元模式。
package cn.edu.tju.app;
public class FlyweightTest {
public static void main(String[] args) {
String str1="hello";
String str2="hello";
String str3=new String("hello");
String str4=new String("hello");
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str3==str4);
System.out.println(str1==str3.intern());
System.out.println(str1==str4.intern());
}
}
定义str1时,会把字符串hello放入字符串常量池,定义str2时,因为字符串常量池中已经存在hello字符串,所以会把str2指向字符串常量池中的hello.
字符串str3通过new创建的对象,所以其指向堆中的字符串hello.
字符串str3通过new创建的对象,所以其指向堆中的字符串hello,其与str3中的hello位于堆中的不通位置。
调用str3.intern()时,因为字符串hello已经在字符串常量池存在(str1),所以返回的是str1所指向的字符串常量池中的hello
调用str4.intern()时,因为字符串hello已经在字符串常量池存在(str1),所以返回的是str1所指向的字符串常量池中的hello
程序输出结果如下: