Flyweight Design Pattern,中文翻译好奇怪。共享元数据的意思吗?
如果系统在运行时产生的对象数量太多,将导致运行代价过高,带来系统性能下降等问题。所以需要采用一个共享来避免大量拥有相同内容对象的开销。在Java中,String类型就是使用了享元模式。String对象是final类型,对象一旦创建就不可改变。在Java中字符串常量都是存在常量池中的,Java会确保一个字符串常量在常量池中只有一个拷贝。
Use sharing to support large numbers of fine-grained objects efficiently
Flyweight design pattern is used when we need to create a lot of Objects of a class. Since every object consumes memory space that can be crucial for low memory devices, such as mobile devices or embedded systems, flyweight design pattern can be applied to reduce the load on memory by sharing objects.
在我们讨论享元模式之前,我们先考虑以下因素:
- 应用程序创建的对象的数量很大。
- 对象的创建很占内存且很消耗时间。
- 状态分为内部状态和外部状态。
内部状态和外部状态:
- 内部状态使对象唯一,存储在享元对象的内部,一般在构造时确定或通过setter设置,并不会随着环境改变而改变的状态,因此内部状态可以共享。
- 外部状态随环境改变而改变,不可以共享的状态。外部状态需要使用时通过客户端传入享元对象。外部状态必须由客户端保存。
Flyweight Design Pattern Interface and Concrete Classes
public interface Shape{
//所有的参数属于外部状态,由客户端保存。
public void draw(Graphice g, int x, int y,int width,int height,Color color);
}
public class Line implements Shape{
public Line(){
System.out.println("Creating Line object");
//adding time delay
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
@Override
public void draw(Graphice g, int x, int y,int width,int height,Color color){
line.setColor(color);
line.drawLine(x1, y1, x2, y2);
}
}
public class Oval implements Shape {
//内部状态,共享,初始化时确定。
private boolean fill;
public Oval(boolean f){
this.fill=f;
System.out.println("Creating Oval object with fill="+f);
//adding time delay
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void draw(Graphics circle, int x, int y, int width, int height, Color color) {
circle.setColor(color);
circle.drawOval(x, y, width, height);
if(fill){
circle.fillOval(x, y, width, height);
}
}
}
Notice that I have intensionally introduced delay in creating the Object of concrete classes to make the point that flyweight pattern can be used for Objects that takes a lot of time while instantiated.
Flyweight Factory
享元模式中,最关键的享元工厂。它将维护已创建的享元实例,并通过实例标记(一般用内部状态)去索引对应的实例,共享实例,实现对象的复用。
The flyweight factory will be used by client programs to instantiate the Object, so we need to keep a map of Objects in the factory that should not be accessible by client application.
Whenever client program makes a call to get an instance of Object, it should be returned from the HashMap, if not found then create a new Object and put in the Map and then return it. We need to make sure that all the intrinsic properties are considered while creating the Object.
Our flyweight factory class looks like below code.
ShapeFactory.java
//创建与提取对象
public class ShapeFactory{
//对象保存,实现对象的复用
public static final HashMap shapes = new HashMap();
public static Shape getShape(ShapeType type){
//对象提取, 享元模式。。
Shape shapeImpl = shapes.get(type);
if(shapeImpl == null){
switch(type){
case ShapeType.OVAL_FILL:
shapeImpl = new Oval(true);
break;
case ShapeType.OVAL_NOFILL:
shapeImpl = new Oval(false);
break;
case ShapeType.LINE:
shapeImpl = new Line();
break;
}
shapes.put(type,shapeImpl);
}
return shapeImpl;
}
public static enum ShapeType{
OVAL_FILL,OVAL_NOFILL,LINE;
}
}
Notice the use of Java Enum for type safety, Java Composition (shapes map) and Factory pattern in getShape method.
Flyweight Design Pattern Client Example
Below is a sample program that consumes flyweight pattern implementation.
DrawingClient.java
public class DrawingClient extends JFrame{
private static final long serialVersionUID = -1350200437285282550L;
private final int WIDTH;
private final int HEIGHT;
private static final ShapeType shapes[] = { ShapeType.LINE, ShapeType.OVAL_FILL,ShapeType.OVAL_NOFILL };
private static final Color colors[] = { Color.RED, Color.GREEN, Color.YELLOW };
public DrawingClient(int width, int height){
this.WIDTH=width;
this.HEIGHT=height;
Container contentPane = getContentPane();
JButton startButton = new JButton("Draw");
final JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(startButton, BorderLayout.SOUTH);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for (int i = 0; i < 20; ++i) {
Shape shape = ShapeFactory.getShape(getRandomShape());
shape.draw(g, getRandomX(), getRandomY(), getRandomWidth(),
getRandomHeight(), getRandomColor());
}
}
});
}
private ShapeType getRandomShape() {
return shapes[(int) (Math.random() * shapes.length)];
}
private int getRandomX() {
return (int) (Math.random() * WIDTH);
}
private int getRandomY() {
return (int) (Math.random() * HEIGHT);
}
private int getRandomWidth() {
return (int) (Math.random() * (WIDTH / 10));
}
private int getRandomHeight() {
return (int) (Math.random() * (HEIGHT / 10));
}
private Color getRandomColor() {
return colors[(int) (Math.random() * colors.length)];
}
public static void main(String[] args) {
DrawingClient drawing = new DrawingClient(500,600);
}
}
总结
比较重要的是享元工厂类,该类用一个HashMap保存了Shape类实例化的各种可能的情况(享元池)。按照初始化参数的组合的情况,每种参数组合存在唯一的实例。享元工厂类本身在系统也只存在一个实例,所以可以用单例模式。
享元模式的精髓是共享,对系统优化非常有好处,感觉像是单例模式的一种拓展。
享元模式的优点:
- 可以极大减少内存中对象的数量,使得相同或相似对象在内存中只保存一份,从而可以节约系统资源,提高系统性能。
- 享元模式的外部状态相对独立,而且不会影响其内部状态,从而使得享元对象可以在不同的环境中被共享。
享元模式缺点:
- 享元模式让系统变得复杂,需要分离出内部状态和外部状态,使得程序的逻辑复杂化。
- 为了使对象可以共享,享元模式需要将享元对象部分状态外部化,而读取外部状态将使得运行时间变长。
其它比较重要的点:
- 如果共享对象的数量很大,那么使用享元模式就是在用空间换时间,所以我们需要根据我们的实际需求衡量是否要使用它。
- 当内部状态数量很多时,最好不要用享元模式,会让享元工厂实现起来很复杂,享元池中存储的对象会很多,而且如果大部分对象使用频率很低的话,导致内存浪费。
非共享享元类
很多文献都提到了非共享享元类(Unshaped Concrete Flyweight),我的理解是继承了享元接口,但不通过享元工厂的享元池保存实例的类。用于满足特殊的需求。