目的

利用共享的方式来支持大量细粒度的对象,这些对象一部分内部状态是相同的。

类图

  • Flyweight:享元对象
  • IntrinsicState:内部状态,享元对象共享内部状态
  • ExtrinsicState:外部状态,每个享元对象的外部状态不同

享元类图.png

实现

  1. public interface Flyweight {
  2. void doOperation(String extrinsicState);
  3. }
  4. public class ConcreteFlyweight implements Flyweight {
  5. private String intrinsicState;
  6. public ConcreteFlyweight(String intrinsicState) {
  7. this.intrinsicState = intrinsicState;
  8. }
  9. @Override
  10. public void doOperation(String extrinsicState) {
  11. System.out.println("Object address: " + System.identityHashCode(this));
  12. System.out.println("IntrinsicState: " + intrinsicState);
  13. System.out.println("ExtrinsicState: " + extrinsicState);
  14. }
  15. }
  16. public class FlyweightFactory {
  17. private HashMap<String, Flyweight> flyweights = new HashMap<>();
  18. Flyweight getFlyweight(String intrinsicState) {
  19. if (!flyweights.containsKey(intrinsicState)) {
  20. Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
  21. flyweights.put(intrinsicState, flyweight);
  22. }
  23. return flyweights.get(intrinsicState);
  24. }
  25. }
  26. public class Client {
  27. public static void main(String[] args) {
  28. FlyweightFactory factory = new FlyweightFactory();
  29. Flyweight flyweight1 = factory.getFlyweight("aa");
  30. Flyweight flyweight2 = factory.getFlyweight("aa");
  31. flyweight1.doOperation("x");
  32. flyweight2.doOperation("y");
  33. }
  34. }
  35. 运行结果
  36. Object address: 1163157884
  37. IntrinsicState: aa
  38. ExtrinsicState: x
  39. Object address: 1163157884
  40. IntrinsicState: aa
  41. ExtrinsicState: y

JDK中的体现

Java 利用缓存来加速大量小对象的访问时间。

  • java.lang.Integer#valueOf(int)
  • java.lang.Boolean#valueOf(boolean)
  • java.lang.Byte#valueOf(byte)
  • java.lang.Character#valueOf(char)