享元模式

2020-05-02  本文已影响0人  jianshujoker

定义

使用共享对象可有效地支持大量的细粒度的对象

细粒度对象

内部状态

外部状态

类图

享元类图.png

应用场景

String

    public static void main(String[] args) {
        String s1 = "hello";//双引号中内容放到字符串常亮池内
        String s2 = "hello";//s1已经声明,s1和s2持有都是hello的引用,hello存储在堆中
        String s3 = "he" + "llo";//编译器优化 s3="hello" s1=s2=s3 hello的引用
        String s4 = "hel" + new String("lo");//存储新的常量hel和lo,产生新的对象lo和hello,s4是新的对象hello
        String s5 = new String("hello");//常量池hello已有,新的hello对象
        //intern将内置加入常量池,进入常量池时已存在返回它的引用,没有加入并返回新的引用,这里相当
        //于s6=s1=s2=s3 hello的引用
        String s6 = s5.intern();
        String s7 = "h";//新的常量池对象h引用
        String s8 = "ello";//新的常量池对象 ello引用
        String s9 = s7 + s8;//新的对象hello
        System.out.println(s1==s2);//true
        System.out.println(s1==s3);//true
        System.out.println(s1==s4);//false
        System.out.println(s1==s9);//false
        System.out.println(s4==s5);//false
        System.out.println(s1==s6);//true
    }

Integer

    public static void main(String[] args) {
        Integer a = Integer.valueOf(100);
        Integer b = 100;

        Integer c = Integer.valueOf(1000);
        Integer d = 1000;

        //a==b:true   c==d:false Integer缓存了[-128,127]的数字
        System.out.println("a==b:" + (a==b));
        System.out.println("c==d:" + (c==d));
    }

优缺点

上一篇 下一篇

猜你喜欢

热点阅读