设计模式(11/23) - 享元模式

104 阅读4分钟

享元模式

1 概述

  • 享元模式(Flyweight Pattern)是一种结构型设计模式,它通过共享对象来最小化内存使用,实现对象的重用。享元模式特别适用于大量相似对象的场景,可以显著减少内存开销。
  • 享元模式将对象的状态分为内部状态和外部状态,内部状态是可以共享的部分,而外部状态是每个对象独有的部分。享元模式通过共享内部状态,减少了内存使用。

2 优缺点及应用场景

2.1 优点

  • 1)减少内存使用:通过共享相同的对象,显著减少内存消耗。
  • 2)提高性能:减少了因大量对象创建带来的性能开销。
  • 3)增强系统的可扩展性:可以更高效地管理和使用大量相似对象。

2.2 缺点

  • 1)增加系统复杂性:需要分离内部状态和外部状态,增加了系统设计和实现的复杂性。
  • 2)使代码逻辑复杂化:为了实现对象的共享,可能需要引入额外的代码来管理状态。

2.3 应用场景

  • 1)Java 中的 String 对象:字符串常量池中已经存在的字符串会被复用。
  • 2)数据库连接池:数据库连接被复用,避免频繁创建和销毁连接。
  • 3)系统中存在大量相似对象:如果系统中有大量相似的对象,可以使用享元模式来减少内存消耗。
  • 4)需要缓解内存压力:在内存资源紧张的情况下,可以使用享元模式来优化内存使用。
  • 5)对象的状态可以分离:当对象的内部状态和外部状态可以分离时,可以使用享元模式。

3 结构

  • 1)享元接口(Flyweight):定义享元对象的接口。
  • 2)具体享元类(ConcreteFlyweight):实现享元接口,并共享内部状态。
  • 3)非共享具体享元类(UnsharedConcreteFlyweight):实现享元接口,但不共享内部状态。
  • 4)享元工厂(FlyweightFactory):创建和管理享元对象,确保合理地共享享元。

4 实现

4.1 UML 类图

享元模式.jpg

4.2 代码示例

// 创建一个接口
interface Shape {
  void draw();
}

// 创建实现接口的实体类:圆形
class Circle implements Shape {
  private String color;
  private int x;
  private int y;
  private int radius;

  public Circle(String color) {
    this.color = color;
  }

  public void setX(int x) {
    this.x = x;
  }

  public void setY(int y) {
    this.y = y;
  }

  public void setRadius(int radius) {
    this.radius = radius;
  }

  @Override
  public void draw() {
    System.out.println("Circle: Draw() [Color : " + color
        + ", x : " + x + ", y :" + y + ", radius :" + radius);
  }
}

// 创建一个工厂,生成基于给定信息的实体类的对象
class ShapeFactory {
  private static final HashMap<String, Shape> circleMap = new HashMap<>();

  public static Shape getCircle(String color) {
    Circle circle = (Circle) circleMap.get(color);

    if (circle == null) {
      circle = new Circle(color);
      circleMap.put(color, circle);
      System.out.println("Creating circle of color : " + color);
    }
    return circle;
  }
}


// 使用示例
public class FlyweightPatternDemo {
  private static final String colors[] = {"Red", "Green", "Blue", "White", "Black"};

  public static void main(String[] args) {
    // 使用该工厂,通过传递颜色信息来获取实体类的对象
    for (int i = 0; i < 20; ++i) {
      Circle circle =
          (Circle) ShapeFactory.getCircle(getRandomColor());
      circle.setX(getRandomX());
      circle.setY(getRandomY());
      circle.setRadius(100);
      circle.draw();
    }
  }

  private static String getRandomColor() {
    return colors[(int) (Math.random() * colors.length)];
  }

  private static int getRandomX() {
    return (int) (Math.random() * 100);
  }

  private static int getRandomY() {
    return (int) (Math.random() * 100);
  }
}
  • 执行程序,输出结果:
Creating circle of color : Black
Circle: Draw() [Color : Black, x : 36, y :71, radius :100
Creating circle of color : Green
Circle: Draw() [Color : Green, x : 27, y :27, radius :100
Creating circle of color : White
Circle: Draw() [Color : White, x : 64, y :10, radius :100
Creating circle of color : Red
Circle: Draw() [Color : Red, x : 15, y :44, radius :100
Circle: Draw() [Color : Green, x : 19, y :10, radius :100
Circle: Draw() [Color : Green, x : 94, y :32, radius :100
Circle: Draw() [Color : White, x : 69, y :98, radius :100
Creating circle of color : Blue
Circle: Draw() [Color : Blue, x : 13, y :4, radius :100
Circle: Draw() [Color : Green, x : 21, y :21, radius :100
Circle: Draw() [Color : Blue, x : 55, y :86, radius :100
Circle: Draw() [Color : White, x : 90, y :70, radius :100
Circle: Draw() [Color : Green, x : 78, y :3, radius :100
Circle: Draw() [Color : Green, x : 64, y :89, radius :100
Circle: Draw() [Color : Blue, x : 3, y :91, radius :100
Circle: Draw() [Color : Blue, x : 62, y :82, radius :100
Circle: Draw() [Color : Green, x : 97, y :61, radius :100
Circle: Draw() [Color : Green, x : 86, y :12, radius :100
Circle: Draw() [Color : Green, x : 38, y :93, radius :100
Circle: Draw() [Color : Red, x : 76, y :82, radius :100
Circle: Draw() [Color : Blue, x : 95, y :82, radius :100

5 总结

  • 享元模式通过共享对象来最小化内存使用,实现对象的重用,特别适用于大量相似对象的场景。享元模式通过将对象的状态分为内部状态和外部状态来实现共享,从而减少内存开销。尽管享元模式可以显著减少内存使用和提高性能,但也增加了系统设计和实现的复杂性。在实际应用中,需要根据具体情况权衡使用享元模式的利弊。