zoukankan      html  css  js  c++  java
  • 设计模式:享元模式

    享元模式

    1 概述

    定义:

    ​ 运用共享技术来有效地支持大量细粒度对象的复用。它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似对象的开销,从而提高系统资源的利用率。

    2 结构

    享元(Flyweight )模式中存在以下两种状态:

    1. 内部状态,即不会随着环境的改变而改变的可共享部分。
    2. 外部状态,指随环境改变而改变的不可以共享的部分。享元模式的实现要领就是区分应用中的这两种状态,并将外部状态外部化。

    享元模式的主要有以下角色:

    • 抽象享元角色(Flyweight):通常是一个接口或抽象类,在抽象享元类中声明了具体享元类公共的方法,这些方法可以向外界提供享元对象的内部数据(内部状态),同时也可以通过这些方法来设置外部数据(外部状态)。
    • 具体享元(Concrete Flyweight)角色 :它实现了抽象享元类,称为享元对象;在具体享元类中为内部状态提供了存储空间。通常我们可以结合单例模式来设计具体享元类,为每一个具体享元类提供唯一的享元对象。
    • 非享元(Unsharable Flyweight)角色 :并不是所有的抽象享元类的子类都需要被共享,不能被共享的子类可设计为非共享具体享元类;当需要一个非共享具体享元类的对象时可以直接通过实例化创建。
    • 享元工厂(Flyweight Factory)角色 :负责创建和管理享元角色。当客户对象请求一个享元对象时,享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。

    代码如下:

    /**
     * @author WGR
     * @create 2021/1/13 -- 21:11
     */
    public  abstract class Animal {
    
        public abstract String getName();
    
        public void getInfo(Integer age){
            System.out.println("age:"+age+",name:"+getName());
        }
    }
    
    
    /**
     * @author WGR
     * @create 2021/1/13 -- 21:18
     */
    public class Cat extends Animal {
        @Override
        public String getName() {
            return "猫";
        }
    }
    
    
    /**
     * @author WGR
     * @create 2021/1/13 -- 21:20
     */
    public class Dog extends Animal  {
        @Override
        public String getName() {
            return "狗";
        }
    }
    
    
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    /**
     * @author WGR
     * @create 2021/1/13 -- 21:25
     */
    public class AnimalFactory {
    
        private static Map<String,Animal> animals = new ConcurrentHashMap<>();
    
        public static Animal getAnimal(String key){
            Animal animal;
            if(!animals.containsKey(key)){
                if("猫".equals(key)){
                    animal = new Cat();
                }else{
                    animal = new Dog();
                }
                animals.put(key, animal);
            }
            return animals.get(key);
    
        };
    }
    
    

    测试代码:

    /**
     * @author WGR
     * @create 2021/1/13 -- 21:34
     */
    public class Test {
    
        public static void main(String[] args) {
            Animal cat1 = AnimalFactory.getAnimal("猫");
            Animal cat2 = AnimalFactory.getAnimal("猫");
            Animal dog = AnimalFactory.getAnimal("狗");
            cat1.getInfo(13);
            cat2.getInfo(12);
            dog.getInfo(11);
            System.out.println(cat1 == cat2);
        }
    }
    
    

    image-20210113215941217

    3 优缺点和使用场景

    1,优点

    • 极大减少内存中相似或相同对象数量,节约系统资源,提供系统性能
    • 享元模式中的外部状态相对独立,且不影响内部状态

    2,缺点:

    为了使对象可以共享,需要将享元对象的部分状态外部化,分离内部状态和外部状态,使程序逻辑复杂

    3,使用场景:

    • 一个系统有大量相同或者相似的对象,造成内存的大量耗费。
    • 对象的大部分状态都可以外部化,可以将这些外部状态传入对象中。
    • 在使用享元模式时需要维护一个存储享元对象的享元池,而这需要耗费一定的系统资源,因此,应当在需要多次重复使用享元对象时才值得使用享元模式。

    4 JDK源码解析

    Integer类使用了享元模式。我们先看下面的例子:

    /**
     * @author WGR
     * @create 2021/1/13 -- 22:00
     */
    public class Demo {
        public static void main(String[] args) {
            Integer i1 = 127;
            Integer i2 = 127;
    
            System.out.println("i1和i2对象是否是同一个对象?" + (i1 == i2));
    
            Integer i3 = 128;
            Integer i4 = 128;
    
            System.out.println("i3和i4对象是否是同一个对象?" + (i3 == i4));
        }
    }
    

    image-20210113220118900

    为什么第一个输出语句输出的是true,第二个输出语句输出的是false?通过反编译软件进行反编译,代码如下:

    public class Demo {
        public static void main(String[] args) {
            Integer i1 = Integer.valueOf((int)127);
            Integer i2 Integer.valueOf((int)127);
            System.out.println((String)new StringBuilder().append((String)"i1u548ci2u5bf9u8c61u662fu5426u662fu540cu4e00u4e2au5bf9u8c61uff1f").append((boolean)(i1 == i2)).toString());
            Integer i3 = Integer.valueOf((int)128);
            Integer i4 = Integer.valueOf((int)128);
            System.out.println((String)new StringBuilder().append((String)"i3u548ci4u5bf9u8c61u662fu5426u662fu540cu4e00u4e2au5bf9u8c61uff1f").append((boolean)(i3 == i4)).toString());
        }
    }
    

    上面代码可以看到,直接给Integer类型的变量赋值基本数据类型数据的操作底层使用的是 valueOf() ,所以只需要看该方法即可

    public final class Integer extends Number implements Comparable<Integer> {
        
    	public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
        
        private static class IntegerCache {
            static final int low = -128;
            static final int high;
            static final Integer cache[];
    
            static {
                int h = 127;
                String integerCacheHighPropValue =
                    sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
                if (integerCacheHighPropValue != null) {
                    try {
                        int i = parseInt(integerCacheHighPropValue);
                        i = Math.max(i, 127);
                        // Maximum array size is Integer.MAX_VALUE
                        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                    } catch( NumberFormatException nfe) {
                    }
                }
                high = h;
                cache = new Integer[(high - low) + 1];
                int j = low;
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
                // range [-128, 127] must be interned (JLS7 5.1.7)
                assert IntegerCache.high >= 127;
            }
    
            private IntegerCache() {}
        }
    }
    

    可以看到 Integer 默认先创建并缓存 -128 ~ 127 之间数的 Integer 对象,当调用 valueOf 时如果参数在 -128 ~ 127 之间则计算下标并从缓存中返回,否则创建一个新的 Integer 对象。

  • 相关阅读:
    微访谈之1:解答各位朋友关心的问题
    深入浅出SQL Server中的死锁(实战篇)
    怎样玩转千万级别的数据
    Another MySQL daemon already running with the same unix socket
    c++ undefined reference to mysqlinit
    Another MySQL daemon already running with the same unix socket
    linxu 挂载分区
    C# RSA
    谷歌地图实现车辆轨迹移动播放(google map api)
    百度地图实现车辆轨迹移动播放(baidu map api)
  • 原文地址:https://www.cnblogs.com/dalianpai/p/14274707.html
Copyright © 2011-2022 走看看