享元模式是一种结构型设计模式,它通过共享对象来减少内存使用和提高性能。在享元模式中,相同的对象只会被创建一次,然后被共享使用。
下面是一个简单的Java代码示例,演示了如何实现享元模式:
import java.util.HashMap;
// 抽象享元类
interface Shape {
void draw();
}
// 具体享元类
class Circle implements Shape {
private String color;
public Circle(String color) {
this.color = color;
}
@Override
public void draw() {
System.out.println("Drawing a circle with color " + color);
}
}
// 享元工厂类
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 a new circle with color " + color);
}
return circle;
}
}
// 客户端代码
public class FlyweightPatternDemo {
private static final String[] colors = {"Red", "Green", "Blue"};
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
Circle circle = (Circle) ShapeFactory.getCircle(getRandomColor());
circle.draw();
}
}
private static String getRandomColor() {
return colors[(int) (Math.random() * colors.length)];
}
}在上面的代码中,我们定义了一个抽象享元类Shape和一个具体享元类Circle。ShapeFactory是享元工厂类,它维护了一个HashMap来存储已经创建的Circle对象。客户端代码通过ShapeFactory来获取Circle对象,并调用draw方法来绘制圆形。
在客户端代码中,我们创建了20个圆形,但是只有3个不同的颜色。因此,只有3个Circle对象被创建,其他的圆形都是共享使用的。这样可以大大减少内存使用和提高性能。
总结:享元模式适用于需要大量创建相似对象的场景,通过共享对象来减少内存使用和提高性能。