11 享元模式(Flyweight Design Pattern

2018-05-28  本文已影响0人  智行孙

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.

在我们讨论享元模式之前,我们先考虑以下因素:

内部状态和外部状态:

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<ShapeType, Shape> shapes = new HashMap<ShapeType, Shape>();

    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),我的理解是继承了享元接口,但不通过享元工厂的享元池保存实例的类。用于满足特殊的需求。

上一篇 下一篇

猜你喜欢

热点阅读