[Design Pattern] Flywight Pattern 簡單案例

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);
    }    
}

 

參考資料

Design Patterns - Flyweight Pattern, TutorialsPoint

相關文章
相關標籤/搜索