/** * 享元模式:简单点说就是使用了缓存的方式,用map或list来存已经创建的对象,获取的时候直接从map或者list中获取就行了,获取不到再new出来,然后再存进去; * 用到的地方有各种常量池,Short在jdk中-128到127的值是缓存在一个数组中,这里使用一个Map简单模拟下缓存模式 * * */ public class ShapeFactory { private static Map<String,Shape> map=new HashMap<>(); public static Shape getShape(String shapeName){ Shape shape = map.get(shapeName); if(null==shape){ shape = new Shape(); map.put(shapeName,shape); } return shape; } } public class Shape { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Test { public static void main(String[] args) { Shape circle1 = ShapeFactory.getShape("circle");//获取圆形 Shape circle2 = ShapeFactory.getShape("circle");//获取圆形 System.out.println(circle1==circle2);//true } }