享元(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;
}
}
}
来源:CSDN
作者:da_kao_la
链接:https://blog.csdn.net/da_kao_la/article/details/104134693