Here's a tutorial I was reading:
http://www.tutorialspoint.com/design_pattern/flyweight_pattern.htm
Here's the code I think is not a flyweight pattern as stated:
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);
}
}
This doesn't seem me a flyweight pattern because according to wikipedia "A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects". In other words, I cannot see an object with intrinsic and extrinsic data. Here I can only see a factory with some sort of caching system.
Can someone demonstrate why this is or is not a flyweight pattern?
When you create a new circle through the ShapeFactory an already created instance is returned, in case one exists for the desired color. This way you can reuse your created instances of Circle (they "share" their data with circles with the same color) and minimize memory consumption.
That said, this code exhibits some problems. Fore example, the Circle objects are mutable so if you start modifying a created circle, all other circles of the same color will also be modified.
And it is utterly thread-unsafe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With