享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。
思考: 通过复用对象来完成工作, 减少对象的创建数量
package day0319.FlayweightPattern;
import java.util.HashMap;
import java.util.Map;
public class Demo{
public static void main(String[] args){
ShapeFactory shapeFactory = new ShapeFactory();
Circle red = (Circle) shapeFactory.getCircle("red");
red.setXYR(3, 3, 3);
red.draw();
Circle bigred = (Circle) shapeFactory.getCircle("red");
bigred.setXYR(3, 3, 10);
bigred.draw();
Circle green = (Circle) shapeFactory.getCircle("green");
green.setXYR(3, 3, 10);
green.draw();
}
}
class ShapeFactory {
Map<String, Shape> hashMap = new HashMap<>();
public Shape getCircle(final String color) {
Shape shape = hashMap.get(color);
if (shape != null) {
System.out.println("[BUILDING] get a circle from map");
return shape;
} else {
System.out.println("[BUILDING] creating a new circle");
Circle circle = new Circle(){{
setColor(color);
}};
hashMap.put(color, circle);
return circle;
}
}
}
interface Shape {
void draw();
}
class Circle implements Shape {
private int x, y, r;
private String color;
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public void setR(int r){
this.r = r;
}
public void setXYR(int x, int y, int r){
this.x = x;
this.y = y;
this.r = r;
}
public void setColor(String color){
this.color = color;
}
@Override
public void draw(){
String template = "%s circle(%s, %s) with %s radis";
System.out.println(String.format(template, this.color, x, y, r));
}
}