Flywight Pattern, 即享元模式,用于减小对象的建立,下降内存的占用,属于结构类的设计模式。根据名字,我也将其会理解为 轻量模式。设计模式
下面是享元模式的一个简单案例。安全
享元模式,主要是重用已有的对象,经过修改部分属性从新使用,避免申请大量内存。dom
本模式须要主要两个点:ide
1. 对象的 key 应该是不可变得,本例中 color 做为 key,因此我在 color 前添加了 final 的修饰符。this
2. 并不是线程安全,多个线程同时获取一个对象,并同时修改其属性,会致使没法预计的结果。spa
代码实现:线程
public interface Shape { public void draw(); }
Circle 类实现 Shape 接口设计
public class Circle implements Shape { private int x; private int y; private int radius; private final String color; public Circle(String color){ this.color = color; } @Override public void draw() { System.out.println(" Circle draw - [" + color + "] x :" + x + ", y :" + y + ", radius :" + radius); } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setRadius(int radius) { this.radius = radius; } }
ShapeFactory 做为一个工厂,提供 Circle 的对象,同时负责重用 color 相同的对象。code
public class ShapeFactory { private HashMap<String, Shape> circleMap = new HashMap<>(); public Shape getCircle(String color){ Shape circle = null; if (circleMap.containsKey(color)){ circle = (Circle)circleMap.get(color); } else{ System.out.println(" Createing cicle - " + color); circle = new Circle(color); circleMap.put(color, circle); } return circle; } }
代码演示,屡次调用工厂 ShapeFactory 得到对象htm
public class FlyweightPatternDemo { static String[] colors = "red,green,blue,black,white".split(","); public static void main(){ ShapeFactory shapeFactory = new ShapeFactory(); shapeFactory.getCircle("red"); for (int i = 0; i < 20; i++){ Circle circle = (Circle)shapeFactory.getCircle(getRandomColor()); circle.setX(getRandomX()); circle.setY(getRandomY()); circle.setRadius(getRandomRadius()); circle.draw(); } } public static String getRandomColor(){ return colors[(int)(Math.random() * colors.length)]; } public static int getRandomX(){ return (int)(Math.random() * 100); } public static int getRandomY(){ return (int)(Math.random() * 100); } public static int getRandomRadius(){ return (int)(Math.random() * 100); } }
参考资料