Is this cartoon drawing really a fly?

Here is the tutorial I was reading:

http://www.tutorialspoint.com/design_pattern/flyweight_pattern.htm

Here's the code I think is not fly agaric as pointed out:

public interface Shape {
   void draw();
}

public 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);
   }
}

import java.util.HashMap;

public 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);
   }
}

      

It doesn't look like flies, because according to wikipedia "Flies are an object that minimizes memory usage by sharing as much data as possible with other similar objects." In other words, I cannot see an object with internal and external data. Here I can only see a factory with some sort of caching system.

Can anyone demonstrate why this is a fly or not?

+3


source to share


1 answer


When you create a new circle through ShapeFactory

, the already created instance is returned if one exists for the desired color. This way you can reuse the instances you create Circle

(they "share" their data with circles of the same color) and minimize memory consumption.

However, this code shows some problems. For example, objects Circle

change, so if you start modifying the created circle, all other circles of the same color will change as well.



And this is absolutely unsafe.

+2


source







All Articles