Skip to main content

Example 2

  • this example is an extension of the first example

  • cache

    • cache/BundledShapedCache.java

      package refactoring_guru.prototype.caching.cache;

      import refactoring_guru.prototype.example.shapes.Circle;
      import refactoring_guru.prototype.example.shapes.Rectangle;
      import refactoring_guru.prototype.example.shapes.Shape;

      import java.util.HashMap;
      import java.util.Map;

      public class BundledShapeCache {
      private Map<String, Shape> cache = new HashMap<>();

      public BundledShapeCache() {
      Circle circle = new Circle();
      circle.x = 5;
      circle.y = 7;
      circle.radius = 45;
      circle.color = "Green";

      Rectangle rectangle = new Rectangle();
      rectangle.x = 6;
      rectangle.y = 9;
      rectangle.width = 8;
      rectangle.height = 10;
      rectangle.color = "Blue";

      cache.put("Big green circle", circle);
      cache.put("Medium blue rectangle", rectangle);
      }

      public Shape put(String key, Shape shape) {
      cache.put(key, shape);
      return shape;
      }

      public Shape get(String key) {
      return cache.get(key).clone();
      }
      }
  • Demo.java

package refactoring_guru.prototype.caching;

import refactoring_guru.prototype.caching.cache.BundledShapeCache;
import refactoring_guru.prototype.example.shapes.Shape;

public class Demo {
public static void main(String[] args) {
BundledShapeCache cache = new BundledShapeCache();

Shape shape1 = cache.get("Big green circle");
Shape shape2 = cache.get("Medium blue rectangle");
Shape shape3 = cache.get("Medium blue rectangle");

if (shape1 != shape2 && !shape1.equals(shape2)) {
System.out.println("Big green circle != Medium blue rectangle (yay!)");
} else {
System.out.println("Big green circle == Medium blue rectangle (booo!)");
}

if (shape2 != shape3) {
System.out.println("Medium blue rectangles are two different objects (yay!)");
if (shape2.equals(shape3)) {
System.out.println("And they are identical (yay!)");
} else {
System.out.println("But they are not identical (booo!)");
}
} else {
System.out.println("Rectangle objects are the same (booo!)");
}
}
}
Big green circle != Medium blue rectangle (yay!)
Medium blue rectangles are two different objects (yay!)
And they are identical (yay!)