主要用于减少创建对象的数量,通常和工厂模式连用。
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("draw circle");
}
}
public class Triangle implements Shape {
@Override
public void draw() {
System.out.println("draw Triangle");
}
}
public class ShapeFlyweightFactory {
private static final HashMap<String, Shape> shapeMap = new HashMap<>(); //对象池
public static String CIRCLE = "circle";
public static String TRIANGLE = "triangle";
public static Shape createShape(String name) {
Shape shape = shapeMap.get(name);
Optional<Shape> shapeOption = Optional.ofNullable(shape);
if (!shapeOption.isPresent()) {
System.out.println("new shape");
switch (name) {
case "circle":
shape = new Circle();
break;
case "triangle":
shape = new Triangle();
break;
default:
break;
}
shapeMap.put(name, shape);
} else {
System.out.println("get shape");
}
return shape;
}
}
@Test
public void FlyweightTest() {
Shape circleNew = ShapeFlyweightFactory.createShape(ShapeFlyweightFactory.CIRCLE);
circleNew.draw();
Shape circleGet = ShapeFlyweightFactory.createShape(ShapeFlyweightFactory.CIRCLE);
circleGet.draw();
}