介紹
享原模式:是結構性模式,主要用於減少創建對象的數量,以減少內存佔用和提高性能。 享元模式和原型模式的區別:原型模式爲了快速創建對象,而享原模式是爲了對象的複用
UML
實現代碼
public class FlyweightPatternDemo {
public static void main(String[] args) {
Shape circle = ShapeFactory.getShape("circle");
circle.drow();
ShapeFactory.getShape("circle");
}
}
/**
* 對象存儲工廠
*/
public class ShapeFactory {
public static final Map<String,Shape> shapeMap = new HashMap<>();
public static Shape getShape(String shapeName){
Shape shape = shapeMap.get(shapeName);
if(shape == null){
if("circle".equals(shapeName)){
shape = new Circle();
shapeMap.put("circle", shape);
}
}
return shape;
}
}
public interface Shape {
void drow();
}
class Circle implements Shape{
public Circle(){
System.out.println("--- create circle ----");
}
@Override
public void drow() {
System.err.println("====circle====");
}
}