【设计模式】享元模式

版权声明:转载请注明出处: https://blog.csdn.net/qq_21687635/article/details/85095149

模式定义

享元模式主要用于减少创建对象的数量,以减少内存占用和提高性能。

下图是该模式的类图:
享元模式类图

一个生动的例子

Flyweight抽象类:
public interface Shape {
	void draw();
}

Flyweight具体类:
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);
	}
}
FlyweightFactory类:
public class ShapeFactory {
	private static final Map<String, Circle> CIRCLE_MAP = new HashMap<>();

	public static Circle getCircle(String color) {
		Circle circle = CIRCLE_MAP.get(color);
		if (circle == null) {
			circle = new Circle(color);
			CIRCLE_MAP.put(color, circle);
			System.out.println("Creating circle of color : " + color);
		}
		return circle;
	}
}
客户端:
public class FlyweightTest {
	private static final String CORLORS[] = { "Red", "Green", "Blue", "White", "Black" };
	private static int length = CORLORS.length;

	public static void main(String[] args) {
		for (int i = 0; i < 20; i++) {
			Circle circle = ShapeFactory.getCircle(getRandomColor());
			circle.setX(getRandomX());
			circle.setY(getRandomY());
			circle.setRadius(100);
			circle.draw();
		}
	}

	private static String getRandomColor() {
		return CORLORS[(int) (Math.random() * length)];
	}

	private static int getRandomX() {
		return (int) (Math.random() * 100);
	}

	private static int getRandomY() {
		return (int) (Math.random() * 100);
	}
}

参考

  1. Head First 设计模式[书籍]
  2. 菜鸟教程之享元模式
  3. 博客园之享元模式

猜你喜欢

转载自blog.csdn.net/qq_21687635/article/details/85095149
今日推荐