这里有一篇我正在阅读的教程:
http://www.tutorialspoint.com/design_pattern/flyweight_pattern.htm
下面是我认为不符合轻量级模式要求的代码:
这似乎不是一个轻量级模式,因为根据维基百科的说法,“轻量级是通过与其他类似对象共享尽可能多的数据来最小化内存使用的对象”。换句话说,我看不到具有固有和外在数据的对象。在这里,我只能看到一个带有某种缓存系统的工厂。
有人能否演示这是否是轻量级模式?
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);
}
}
这似乎不是一个轻量级模式,因为根据维基百科的说法,“轻量级是通过与其他类似对象共享尽可能多的数据来最小化内存使用的对象”。换句话说,我看不到具有固有和外在数据的对象。在这里,我只能看到一个带有某种缓存系统的工厂。
有人能否演示这是否是轻量级模式?