享元模式

血红的双手。 提交于 2020-02-02 01:23:30

享元(Flyweight, 『轻量级』)模式,指的是一种构造对象时对于完全相同的对象直接返回之前已经构造的对象而无需重新构造的设计模式,用于大量创建相同对象的场景,减小内存使用。享元模式的关键是享元工厂类中用于缓存享元对象的哈希表。Java的字符串常量池就是享元模式的典型应用。
下面用一个字符封装类SharedCharacter为例介绍享元模式,通过享元模式,同样的字符用同一个封装类对象,无需构造大量的字符对象。
驱动类:Main.java

public class Main {
    public static void main(String[] args) {
        SharedCharacter scA = SharedCharacterFactory.getSharedCharacter('a');
        SharedCharacter scB = SharedCharacterFactory.getSharedCharacter('b');
        SharedCharacter scA1 = SharedCharacterFactory.getSharedCharacter('a');
        System.out.println("scA: " + scA + ", scB: " + scB + ", scA1: " + scA1);
        // scA: a, scB: b, scA1: a
        System.out.println("Character \'a\' is cached or not? " + (scA == scA1));
        // Character 'a' is cached or not? true
    }
}

享元字符封装类:SharedCharacter.java

public class SharedCharacter {
    private char ch;

    public SharedCharacter(char ch) {
        this.ch = ch;
    }

    @Override
    public String toString() {
        return String.valueOf(ch);
    }
}

享元工厂类:SharedCharacterFactory.java

import java.util.HashMap;

public class SharedCharacterFactory {
    private static HashMap<Character, SharedCharacter> pool = new HashMap<>();

    public static SharedCharacter getSharedCharacter(char ch) {
        if (pool.containsKey(ch)) {
            return pool.get(ch);
        } else {
            SharedCharacter sc = new SharedCharacter(ch);
            pool.put(ch, sc);
            return sc;
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!