概念:运用共享技术有效地支持大量细粒度的对象
核心:共享内存,划分内部状态与外部状态,外部状态在使用的时候传递进来
作用:本地缓存

享元模式结构图

image.png

java代码

  1. public class FlyWeightTest {
  2. public static void main(String[] args) {
  3. FlyWeightFactory f = new FlyWeightFactory();
  4. int index = 22;
  5. FlyWeight x = f.GetFlyWeight("X");
  6. x.Operation(index--);
  7. FlyWeight y = f.GetFlyWeight("Y");
  8. x.Operation(index--);
  9. FlyWeight z = f.GetFlyWeight("Z");
  10. x.Operation(index--);
  11. UnSharedConcreteFlyWeight unSharedConcreteFlyWeight = new UnSharedConcreteFlyWeight();
  12. unSharedConcreteFlyWeight.Operation(index--);
  13. }
  14. }
  15. //享元工厂
  16. public class FlyWeightFactory {
  17. Map<String, FlyWeight> map = new HashMap<>();
  18. public FlyWeight GetFlyWeight(String key){
  19. return map.get(key);
  20. }
  21. public FlyWeightFactory(){
  22. map.put("X", new ConcreteFlyWeight());
  23. map.put("Y", new ConcreteFlyWeight());
  24. map.put("Z", new ConcreteFlyWeight());
  25. }
  26. }
  27. public abstract class FlyWeight {
  28. public abstract void Operation(int index);
  29. }
  30. public class UnSharedConcreteFlyWeight extends FlyWeight {
  31. @Override
  32. public void Operation(int index) {
  33. System.out.println("不共享的类" + index);
  34. }
  35. }
  36. public class ConcreteFlyWeight extends FlyWeight {
  37. @Override
  38. public void Operation(int index) {
  39. System.out.println("共享的类" + index);
  40. }
  41. }