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 String getColor () {
return color;
}
public void setColor (String color) {
this .color = color;
}
public int getX () {
return x;
}
public void setX (int x) {
this .x = x;
}
public int getY () {
return y;
}
public void setY (int y) {
this .y = y;
}
public int getRadius () {
return radius;
}
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<String, Shape>();
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 {
/**
* 执行过程:
* 1、设置colors的颜色
*
* **/
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();
}
}
/**
* 返回随机颜色
* @return
*/
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 );
}
}