轻量级模式用于减少对象的数量,减少内存的使用以及增加程序的性能。它通过重复利用已存在的相似的对象来达到减少对象数量,如果没有相匹配的对象则会创建新的对象。
本例中需要画20个不同位置的圆,但是只创建5个对象。
public interface Shape {
void draw();
}
import java.util.HashMap;
/**
* Created by wang on 16-12-17.
*/
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 circel of color: " + color);
}
return circle;
}
}
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: ");
System.out.println(x + ", y: " + y + ",radius: " + radius);
}
}
public class Demo {
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();
}
}
public static String getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
public static int getRandomX() {
return (int)(Math.random()*100);
}
public static int getRandomY() {
return (int)(Math.random()*100);
}
}
输出:
Creating circel of color: Red
Circle: Draw() [Color: Red, x:
10, y: 87,radius: 100
Creating circel of color: Black
Circle: Draw() [Color: Black, x:
5, y: 32,radius: 100
Creating circel of color: Blue
Circle: Draw() [Color: Blue, x:
50, y: 29,radius: 100
Creating circel of color: Green
Circle: Draw() [Color: Green, x:
12, y: 67,radius: 100
Creating circel of color: White
Circle: Draw() [Color: White, x:
64, y: 97,radius: 100
Circle: Draw() [Color: Blue, x:
38, y: 18,radius: 100
Circle: Draw() [Color: Black, x:
23, y: 29,radius: 100
Circle: Draw() [Color: Red, x:
78, y: 58,radius: 100
Circle: Draw() [Color: Green, x:
65, y: 33,radius: 100
Circle: Draw() [Color: Black, x:
98, y: 19,radius: 100
Circle: Draw() [Color: Green, x:
80, y: 91,radius: 100
Circle: Draw() [Color: Blue, x:
59, y: 30,radius: 100
Circle: Draw() [Color: White, x:
88, y: 82,radius: 100
Circle: Draw() [Color: Green, x:
36, y: 93,radius: 100
Circle: Draw() [Color: Green, x:
6, y: 12,radius: 100
Circle: Draw() [Color: Blue, x:
22, y: 76,radius: 100
Circle: Draw() [Color: Blue, x:
8, y: 20,radius: 100
Circle: Draw() [Color: White, x:
99, y: 55,radius: 100
Circle: Draw() [Color: White, x:
38, y: 67,radius: 100
Circle: Draw() [Color: Blue, x:
31, y: 84,radius: 100