运用共享技术有效地支持大量细粒度的对象。
主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。
关键存储对象:HashMap
public class Flyweight_Main {
public static void main(String[] args) {
CircleFactory circleFactory = new CircleFactory();
for (int i=0;i<=10;i++){
Circle whiteCircle = circleFactory.get(WhiteCircle.class.getName());
whiteCircle.show();
}
}
}
abstract class Circle{
abstract String circleName();
void show(){
System.out.println(this.circleName());
}
}
class WhiteCircle extends Circle{
@Override
String circleName() {
return "白色";
}
}
class RedCircle extends Circle{
@Override
String circleName() {
return "白色";
}
}
class CircleFactory{
private static final Map<String,Circle> CIRCLE_MAP = new ConcurrentHashMap<>();
public Circle get(String className){
if (StringUtils.isEmpty(className))return null;
Circle circle = CIRCLE_MAP.get(className);
if (circle == null){
System.out.println("进行实例化....className is " + className);
try {
circle = (Circle) Class.forName(className).newInstance();
CIRCLE_MAP.put(className,circle);
} catch (Exception e) {
e.printStackTrace();
}
}
return circle;
}
}