设计模式之亨元 Flyweight

重点

将已创建的对象保存在内存,避免相同的对象反复创建

场景

大量相似的对象
缓冲池

public interface Shape {
   void draw();
}

public class Circle implements Shape {
   private String color;

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

   @Override
   public void draw() {
      System.out.println(String.format("draw %s circle", color));
   }
}

public class ShapeFactory {
   private static final HashMap 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;
   }
}

你可能感兴趣的:(设计模式之亨元 Flyweight)