13.Flyweight-享元模式

Flyweight 享元模式

  • 享元模式模式:
    享元模式的主要目的是實現對象的共享,即共享池,當系統中對象多的時候可以減少內存的開銷,
    意圖在於運用共享技術有效地支持大量細粒度的對象。
    由於享元模式要求能夠共享的對象必須是細粒度對象,因此它又稱爲輕量級模式,它是一種對象結構型模式。
    通常與工廠模式一起使用。

它使用共享物件,用來儘可能減少內存使用量以及分享資訊給儘可能多的相似物件;
它適合用於當大量物件只是重複因而導致無法令人接受的使用大量內存。通常物件中的部分狀態是可以分享。
常見做法是把它們放在外部數據結構,當需要使用時再將它們傳遞給享元。

  • 結構圖:
    Flyweight_structure

  • 示例類圖:
    Flyweight_uml

  • 示例代碼:

public class ShapeFactory {
    private static final HashMap<String, Shape> circleMap = new HashMap<String, Shape>();

    public static Shape getCircle(String color) {
        Circle circle = (Circle) circleMap.get(color);
        if (circle == null) {
            circle = new Circle(color);
            circleMap.put(color, circle);
            System.out.println("Creating circle of color : " + color);
        }
        return circle;
    }
}

public class Circle implements Shape {
    private String color;
    private int x;
    private int y;
    private int radius;

    public Circle(String color) {
        this.color = color;
    }

    @Override
    public void draw() {
        System.out.println("Circle: Draw() [Color : " + 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;
    }
}

public class ShapeFactory {
    private static final HashMap<String, Shape> circleMap = new HashMap<String, Shape>();

    public static Shape getCircle(String color) {
        Circle circle = (Circle) circleMap.get(color);
        if (circle == null) {
            circle = new Circle(color);
            circleMap.put(color, circle);
            System.out.println("Creating circle of color : " + color);
        }
        return circle;
    }
}

public class FlyweightTest {
    static String colors[] = { "Red", "Green", "Blue", "White", "Black" };

    public static void main(String[] args) {
        for (int i = 0; i < 10; ++i) {
            Circle circle = (Circle) ShapeFactory.getCircle(getRandomColor());
            circle.setX(getRandomX());
            circle.setY(getRandomY());
            circle.setRadius(100);
            circle.draw();
        }
    }
    private static String getRandomColor() {
        return colors[(int) (Math.random() * colors.length)];
    }
    private static int getRandomX() {
        return (int) (Math.random() * 100);
    }
    private static int getRandomY() {
        return (int) (Math.random() * 100);
    }
}
  • 適用範圍:

    1. 一個應用程序使用了大量的對象。
    2. 完全由於使用大量的對象,造成很大的存儲開銷。
    3. 對象的大多數狀態都可變爲外部狀態。
    4. 如果刪除對象的外部狀態,那麼可以用相對較少的共享對象取代很多組對象。
    5. 應用程序不依賴於對象標識。由於Flyweigft對象可以被共享,對於概念上明顯有別的對象,標識測試將返回真值。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章